Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Command Center (MCC)8 * File : services/internal/identity/vauth/vauth.go9 * Module : services10 * Repository : https://git.spboucher.ai/maclustr-command-center11 * Project Website : https://clustr.spboucher.ai12 * Created : 2026-11-1813 * Last Modified : 2026-11-1814 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Package vauth is a software WebAuthn authenticator used by automated tests43// (Go integration tests and end-to-end harnesses). It produces real,44// cryptographically valid attestation and assertion responses (ES256,45// attestation format "none"), and can be told to misbehave in specific ways46// to exercise the server's defences. It is never linked into a service binary.47package vauth4849import (50 "crypto/ecdsa"51 "crypto/elliptic"52 "crypto/rand"53 "crypto/sha256"54 "encoding/base64"55 "encoding/binary"56 "encoding/json"57 "errors"58 "fmt"5960 "github.com/fxamacker/cbor/v2"61)6263type credential struct {64 id []byte65 key *ecdsa.PrivateKey66 rpID string67 userHandle []byte68 counter uint3269}7071// Authenticator holds discoverable credentials, like a platform passkey provider.72type Authenticator struct {73 Origin string // origin reported in clientDataJSON74 // Behaviour switches (all false/zero = a well-behaved synced passkey provider).75 NoUserVerification bool // do not set the UV flag76 UseCounter bool // increment a signature counter (device-bound style)77 RPIDOverride string // hash this RP ID instead of the requested one78 creds []*credential79}8081func New(origin string) *Authenticator { return &Authenticator{Origin: origin} }8283var b64 = base64.RawURLEncoding8485type creationOptions struct {86 PublicKey struct {87 Challenge string `json:"challenge"`88 RP struct {89 ID string `json:"id"`90 } `json:"rp"`91 User struct {92 ID string `json:"id"`93 } `json:"user"`94 ExcludeCredentials []struct {95 ID string `json:"id"`96 } `json:"excludeCredentials"`97 } `json:"publicKey"`98}99100type requestOptions struct {101 PublicKey struct {102 Challenge string `json:"challenge"`103 RPID string `json:"rpId"`104 AllowCredentials []struct {105 ID string `json:"id"`106 } `json:"allowCredentials"`107 } `json:"publicKey"`108}109110func (a *Authenticator) clientData(typ, challenge string) []byte {111 b, _ := json.Marshal(map[string]any{"type": typ, "challenge": challenge, "origin": a.Origin, "crossOrigin": false})112 return b113}114115func (a *Authenticator) flags(attested bool) byte {116 f := byte(0x01) // UP117 if !a.NoUserVerification {118 f |= 0x04119 }120 if !a.UseCounter {121 f |= 0x08 | 0x10 // backup eligible + backed up: a synced passkey122 }123 if attested {124 f |= 0x40125 }126 return f127}128129func (a *Authenticator) rpHash(rpID string) []byte {130 if a.RPIDOverride != "" {131 rpID = a.RPIDOverride132 }133 h := sha256.Sum256([]byte(rpID))134 return h[:]135}136137// Create answers navigator.credentials.create(): options is the JSON object138// {"publicKey": {...}} returned by the server; the result is the JSON a139// browser would post back.140func (a *Authenticator) Create(options []byte) ([]byte, error) {141 var o creationOptions142 if err := json.Unmarshal(options, &o); err != nil {143 return nil, err144 }145 for _, ex := range o.PublicKey.ExcludeCredentials {146 for _, c := range a.creds {147 if b64.EncodeToString(c.id) == ex.ID {148 return nil, errors.New("vauth: InvalidStateError (credential excluded)")149 }150 }151 }152 userHandle, err := b64.DecodeString(o.PublicKey.User.ID)153 if err != nil {154 return nil, fmt.Errorf("vauth: user.id: %w", err)155 }156 key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)157 if err != nil {158 return nil, err159 }160 c := &credential{id: make([]byte, 32), key: key, rpID: o.PublicKey.RP.ID, userHandle: userHandle}161 rand.Read(c.id)162163 x, y := make([]byte, 32), make([]byte, 32)164 key.X.FillBytes(x)165 key.Y.FillBytes(y)166 cose, err := cbor.Marshal(map[int]any{1: 2, 3: -7, -1: 1, -2: x, -3: y})167 if err != nil {168 return nil, err169 }170 authData := append([]byte{}, a.rpHash(c.rpID)...)171 authData = append(authData, a.flags(true))172 authData = binary.BigEndian.AppendUint32(authData, 0)173 authData = append(authData, make([]byte, 16)...) // AAGUID: zeros174 authData = binary.BigEndian.AppendUint16(authData, uint16(len(c.id)))175 authData = append(authData, c.id...)176 authData = append(authData, cose...)177 att, err := cbor.Marshal(map[string]any{"fmt": "none", "attStmt": map[string]any{}, "authData": authData})178 if err != nil {179 return nil, err180 }181 a.creds = append(a.creds, c)182 return json.Marshal(map[string]any{183 "id": b64.EncodeToString(c.id), "rawId": b64.EncodeToString(c.id), "type": "public-key",184 "authenticatorAttachment": "platform", "clientExtensionResults": map[string]any{},185 "response": map[string]any{186 "clientDataJSON": b64.EncodeToString(a.clientData("webauthn.create", o.PublicKey.Challenge)),187 "attestationObject": b64.EncodeToString(att),188 "transports": []string{"internal"},189 },190 })191}192193// Get answers navigator.credentials.get().194func (a *Authenticator) Get(options []byte) ([]byte, error) {195 var o requestOptions196 if err := json.Unmarshal(options, &o); err != nil {197 return nil, err198 }199 var c *credential200 for _, cand := range a.creds {201 if cand.rpID != o.PublicKey.RPID {202 continue203 }204 if len(o.PublicKey.AllowCredentials) == 0 {205 c = cand206 }207 for _, al := range o.PublicKey.AllowCredentials {208 if al.ID == b64.EncodeToString(cand.id) {209 c = cand210 }211 }212 }213 if c == nil {214 return nil, errors.New("vauth: NotAllowedError (no matching credential)")215 }216 return a.assert(c, o.PublicKey.Challenge)217}218219func (a *Authenticator) assert(c *credential, challenge string) ([]byte, error) {220 if a.UseCounter {221 c.counter++222 }223 authData := append([]byte{}, a.rpHash(c.rpID)...)224 authData = append(authData, a.flags(false))225 authData = binary.BigEndian.AppendUint32(authData, c.counter)226 cd := a.clientData("webauthn.get", challenge)227 cdHash := sha256.Sum256(cd)228 digest := sha256.Sum256(append(append([]byte{}, authData...), cdHash[:]...))229 sig, err := ecdsa.SignASN1(rand.Reader, c.key, digest[:])230 if err != nil {231 return nil, err232 }233 return json.Marshal(map[string]any{234 "id": b64.EncodeToString(c.id), "rawId": b64.EncodeToString(c.id), "type": "public-key",235 "authenticatorAttachment": "platform", "clientExtensionResults": map[string]any{},236 "response": map[string]any{237 "clientDataJSON": b64.EncodeToString(cd), "authenticatorData": b64.EncodeToString(authData),238 "signature": b64.EncodeToString(sig), "userHandle": b64.EncodeToString(c.userHandle),239 },240 })241}242243// RewindCounter lowers every credential's counter, simulating a cloned authenticator replaying old state.244func (a *Authenticator) RewindCounter(by uint32) {245 for _, c := range a.creds {246 if c.counter >= by {247 c.counter -= by248 } else {249 c.counter = 0250 }251 }252}253254// Count returns the number of stored credentials.255func (a *Authenticator) Count() int { return len(a.creds) }256257// Forget drops all credentials (a wiped device).258func (a *Authenticator) Forget() { a.creds = nil }259