package governance import ( "context" "crypto/subtle" "errors" "net" "net/http" "strings" "time" "github.com/samcharles93/archie-core/internal/platform/httpapi" "github.com/samcharles93/archie-core/internal/platform/httpjson" ) // credentials is what authenticating a request reads. type credentials interface { ResolveAccountSession(context.Context, string) (Identity, error) ResolveSubject(context.Context, Subject) (Identity, error) PersonalTokenOf(context.Context, Subject) (PersonalToken, error) TouchPersonalToken(context.Context, Subject, time.Time) error PrincipalFor(context.Context, IdentityID) (Principal, error) } // authenticator admits, in order, a browser session cookie, a personal API // token, or the bootstrap admin token, which is held only as its hash. type authenticator struct { creds credentials adminHash string now func() time.Time } // Authenticator returns the API's authenticator over the module's accounts // and personal tokens, with adminHash the bootstrap admin token's hash. func (m *Module) Authenticator(adminHash string) httpapi.Authenticator { return authenticator{creds: m, adminHash: adminHash, now: time.Now} } func (a authenticator) Authenticate(ctx context.Context, r *http.Request) (context.Context, bool, error) { if c, err := r.Cookie(httpapi.SessionCookie); err == nil { value, err := a.creds.ResolveAccountSession(ctx, c.Value) return a.acting(ctx, value, err) } token, ok := bearer(r) if !ok { return nil, false, httpapi.ErrUnauthenticated } if subject, ok := PersonalTokenSubject(token); ok { if err := UsePersonalToken(ctx, a.creds, subject, a.now()); err != nil { return a.acting(ctx, Identity{}, err) } value, err := a.creds.ResolveSubject(ctx, subject) return a.acting(ctx, value, err) } if httpjson.TokenMatches(token, a.adminHash) { return actingAs(ctx, SharedTokenOwner()), true, nil } return nil, false, httpapi.ErrUnauthenticated } // acting is the principal an identity resolved from a credential acts as. func (a authenticator) acting(ctx context.Context, value Identity, err error) (context.Context, bool, error) { if err == nil && !value.CanAct() { err = ErrIdentityInactive } if err != nil { if refused(err) { return nil, false, httpapi.ErrUnauthenticated } return nil, false, err } p, err := a.creds.PrincipalFor(ctx, value.ID) if err != nil { return nil, false, err } p.Kind = value.Kind return actingAs(ctx, p), p.InstanceAdmin(), nil } func actingAs(ctx context.Context, p Principal) context.Context { return WithOrg(WithPrincipal(ctx, p), p.Org) } // refused reports whether err says the credential was not accepted, as // opposed to the lookup failing. func refused(err error) bool { for _, target := range []error{ErrNoCredential, ErrCredentialRejected, ErrIdentityNotFound, ErrIdentityInactive, ErrSubjectUnbound} { if errors.Is(err, target) { return true } } return false } func bearer(r *http.Request) (string, bool) { const prefix = "Bearer " header := r.Header.Get("Authorization") if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) { return "", false } token := strings.TrimSpace(header[len(prefix):]) return token, token != "" } // loopback reports whether host, as a request's Host header gives it, names // this machine. Browsers send a Secure cookie only over HTTPS, except to // localhost. func loopback(host string) bool { if name, _, err := net.SplitHostPort(host); err == nil { host = name } host = strings.Trim(host, "[]") if strings.EqualFold(host, "localhost") { return true } ip := net.ParseIP(host) return ip != nil && ip.IsLoopback() } func sameToken(got, want string) bool { return subtle.ConstantTimeCompare([]byte(got), []byte(want)) == 1 }