mirror of
https://github.com/hanzoai/ca.git
synced 2026-11-03 18:08:27 +00:00
* Fix issues F-003, 006, 001, 022
* Fix issues F-025, 026, 010, 008
- Login tokens name their identity provider in the `provider` claim;
SelectOrg and GetUserToken read it with pb.IDPFromString, which also
takes the number older tokens carry, and AuthenticateAPIKey answers
Provider Undefined.
- A login that fails after the callback decodes its state lands on the
redirect URI of the client, in its response mode, with `error` and
`error_description` (RFC 6749 section 4.1.2.1); a server-side failure
is described by its status text only. The calls to an IdP take the
request context and a client with a timeout, and the answer of the IdP
stays in the server log.
- The platform bootstrap reads its ca-config with ca.LoadBootstrapConfig,
which refuses an issuer URL template with `${ISSUER_ID}` or
`$ISSUER_ID`: the loader expands them to an empty string. The proto,
README and CLI help name `:ISSUER_ID`.
- CaDb.RegisterIssuer takes the trust anchor of a root issuer and writes
both in one transaction; the backend service and the bootstrap pass it,
and an anchor registered in another scope is AlreadyExists.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* Address PR review comments
- Invite acceptance deletes the invite in its transaction
(query.TakeInvite, DELETE ... RETURNING) and grants from the deleted
row: a withdrawn or already accepted invite grants nothing, a re-issued
one grants its current role, and an email mismatch, an expired invite or
a failed grant rolls the delete back.
- CaDb.RegisterIssuer requires the anchor of a root issuer and refuses one
for any other issuer; the service always builds it for a root.
- The OAuth response is merged into the query of a redirect URI that has
one, and replaces its fragment in fragment mode.
- The codemap describes the transactions of RegisterOrg and the invite
acceptance.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---------
Co-authored-by: Claude Opus 5.5 <[email protected]>
216 lines
6.5 KiB
Go
216 lines
6.5 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/effective-security/porto/restserver"
|
|
"github.com/effective-security/porto/xhttp/header"
|
|
"github.com/effective-security/porto/xhttp/httperror"
|
|
"github.com/effective-security/porto/xhttp/identity"
|
|
"github.com/effective-security/porto/xhttp/marshal"
|
|
"github.com/effective-security/trustyca/api/pb"
|
|
"github.com/effective-security/trustyca/internal/authctx"
|
|
"github.com/effective-security/trustyca/internal/events"
|
|
"github.com/effective-security/x/values"
|
|
"github.com/effective-security/xpki/jwt"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/protobuf/types/known/emptypb"
|
|
)
|
|
|
|
// UserinfoHandler returns handler for returning the user info
|
|
func (s *Service) UserinfoHandler() restserver.Handle {
|
|
return func(w http.ResponseWriter, r *http.Request, _ restserver.Params) {
|
|
caller := identity.FromRequest(r).Identity()
|
|
claims := caller.Claims()
|
|
//logger.KV(xlog.DEBUG, "claims", claims)
|
|
|
|
marshal.WritePlainJSON(w, http.StatusOK, claims, marshal.PrettyPrint)
|
|
}
|
|
}
|
|
|
|
// GetUserToken returns the user token info
|
|
func (s *Service) GetUserToken(ctx context.Context, _ *emptypb.Empty) (*pb.UserTokenResponse, error) {
|
|
caller := identity.FromContext(ctx).Identity()
|
|
|
|
var claims jwt.Claims
|
|
mapclaims := caller.Claims()
|
|
err := mapclaims.To(&claims)
|
|
if err != nil {
|
|
return nil, httperror.WrapWithCtx(ctx, err, "request failed")
|
|
}
|
|
|
|
res := &pb.UserTokenResponse{
|
|
Token: &pb.Token{
|
|
TokenType: caller.TokenType(),
|
|
// If the authentication method is JWT Cookie, do not return the access token
|
|
AccessToken: values.Select(caller.AuthMethod() == identity.MethodJWTCookie, "", caller.AccessToken()),
|
|
ExpiresAt: mapclaims.TimeVal("exp").Format(time.RFC3339),
|
|
IssuedAt: mapclaims.TimeVal("iat").Format(time.RFC3339),
|
|
Issuer: mapclaims.String("iss"),
|
|
Audience: mapclaims.String("aud"),
|
|
Provider: tokenProvider(mapclaims),
|
|
},
|
|
UserInfo: &pb.UserInfo{
|
|
ID: claims.Subject,
|
|
Name: claims.Name,
|
|
Email: claims.Email,
|
|
EmailVerified: claims.EmailVerified,
|
|
Role: caller.Role(),
|
|
OrgID: mapclaims.String(authctx.ClaimOrg),
|
|
OrgRole: mapclaims.String(authctx.ClaimOrgRole),
|
|
OrgRoleSource: mapclaims.String(authctx.ClaimOrgRoleSource),
|
|
},
|
|
}
|
|
if claims.Cnf != nil {
|
|
res.Token.Jkt = claims.Cnf.Jkt
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// UserTokenHandler returns UserTokenResponse
|
|
func (s *Service) UserTokenHandler() restserver.Handle {
|
|
return func(w http.ResponseWriter, r *http.Request, _ restserver.Params) {
|
|
res, err := s.GetUserToken(r.Context(), nil)
|
|
if err != nil {
|
|
marshal.WriteJSON(w, r, err)
|
|
return
|
|
}
|
|
marshal.WriteJSON(w, r, &res)
|
|
}
|
|
}
|
|
|
|
// Caller returns the status of the caller.
|
|
func (s *Service) Caller(ctx context.Context, _ *emptypb.Empty) (*pb.CallerStatusResponse, error) {
|
|
callerCtx := identity.FromContext(ctx)
|
|
caller := callerCtx.Identity()
|
|
|
|
res := &pb.CallerStatusResponse{
|
|
Subject: caller.Subject(),
|
|
Role: caller.Role(),
|
|
}
|
|
|
|
cl := caller.Claims()
|
|
if len(cl) > 0 {
|
|
res.Claims = make([]*pb.KVPair, 0, len(cl))
|
|
for k := range cl {
|
|
res.Claims = append(res.Claims, &pb.KVPair{Key: k, Value: cl.String(k)})
|
|
}
|
|
}
|
|
|
|
return res, nil
|
|
}
|
|
|
|
func (s *Service) callerStatus() restserver.Handle {
|
|
return func(w http.ResponseWriter, r *http.Request, _ restserver.Params) {
|
|
callerCtx := identity.FromRequest(r)
|
|
caller := callerCtx.Identity()
|
|
|
|
res := &pb.CallerStatusResponse{
|
|
Subject: caller.Subject(),
|
|
Role: caller.Role(),
|
|
}
|
|
|
|
cl := caller.Claims()
|
|
if len(cl) > 0 {
|
|
res.Claims = make([]*pb.KVPair, 0, len(cl))
|
|
for k := range cl {
|
|
res.Claims = append(res.Claims, &pb.KVPair{Key: k, Value: cl.String(k)})
|
|
}
|
|
}
|
|
|
|
accept := r.Header.Get(header.Accept)
|
|
if accept == "" || strings.EqualFold(accept, header.ApplicationJSON) {
|
|
marshal.WriteJSON(w, r, res)
|
|
} else {
|
|
w.Header().Set(header.ContentType, header.TextPlain)
|
|
// TODO: print
|
|
// res.Print(w)
|
|
marshal.WriteJSON(w, r, res)
|
|
}
|
|
}
|
|
}
|
|
|
|
// RevokeToken revokes the user token
|
|
func (s *Service) RevokeToken(ctx context.Context, _ *emptypb.Empty) (*emptypb.Empty, error) {
|
|
err := s.revoke(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &emptypb.Empty{}, nil
|
|
}
|
|
|
|
func (s *Service) revoke(ctx context.Context) error {
|
|
ictx := identity.FromContext(ctx)
|
|
caller := ictx.Identity()
|
|
if caller.AccessToken() == "" {
|
|
// a guest has no token to revoke, and nobody signs out
|
|
return httperror.NewGrpcFromCtx(ctx, codes.Unauthenticated, "no token to revoke")
|
|
}
|
|
mapclaims := caller.Claims()
|
|
revocation := s.JwtParser.GetRevocation()
|
|
if revocation == nil {
|
|
return httperror.NewGrpcFromCtx(ctx, codes.Unimplemented, "revocation not supported")
|
|
}
|
|
|
|
err := revocation.Revoke(ctx, caller.AccessToken(), mapclaims)
|
|
if err != nil {
|
|
return httperror.WrapWithCtx(ctx, err, "request failed")
|
|
}
|
|
|
|
tctx := authctx.FromContext(ctx)
|
|
jti := mapclaims.String("jti")
|
|
if tctx.IsAPIKey() {
|
|
// the subject of an API key token is the key: no user signs out
|
|
events.New(ctx, ServiceName, pb.EventType_TokenRevoked, "Token revoked").
|
|
Org(tctx.OrgID()).
|
|
Project(tctx.ProjectID()).
|
|
Reference(tctx.UserID()).
|
|
Description("API key token %s revoked", jti).
|
|
Emit(s.db)
|
|
return nil
|
|
}
|
|
|
|
events.New(ctx, ServiceName, pb.EventType_UserSignedOut, "User signed out").
|
|
Org(tctx.OrgID()).
|
|
Reference(tctx.UserID()).
|
|
Description("%s signed out and revoked token %s", tctx.Email(), jti).
|
|
Emit(s.db)
|
|
|
|
return nil
|
|
}
|
|
|
|
// RevokeTokenHandler handles DELETE /pb.Auth/RevokeToken, the sign-out of a
|
|
// REST caller and of a cookie session: it removes the auth and CSRF cookies
|
|
// whatever the outcome, then revokes the caller's token
|
|
func (s *Service) RevokeTokenHandler() restserver.Handle {
|
|
return func(w http.ResponseWriter, r *http.Request, _ restserver.Params) {
|
|
ctx := r.Context()
|
|
ccfg := s.server.Configuration().IdentityMap.GetCookiesConfig()
|
|
resetAuthCookie(w, ccfg)
|
|
|
|
err := s.revoke(ctx)
|
|
if err != nil {
|
|
// revoke returns sanitized errors: a guest's, a revocation the
|
|
// server does not support, or a failed revocation
|
|
marshal.WriteJSON(w, r, err)
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
}
|
|
|
|
// GetAllowedMethods returns the allowed methods for the caller
|
|
func (s *Service) GetAllowedMethods(ctx context.Context, req *emptypb.Empty) (*pb.ServiceAccessInfo, error) {
|
|
return authctx.GetAllowedMethods(ctx, s.authorizer)
|
|
}
|
|
|
|
// GetCallerScope returns the caller's resolved scope and the method access rules
|
|
func (s *Service) GetCallerScope(ctx context.Context, req *emptypb.Empty) (*pb.CallerScope, error) {
|
|
return authctx.GetCallerScope(ctx, s.authorizer)
|
|
}
|