feat(consent): add versioned append-only consent ledger C1-C5

This commit is contained in:
shira committed 2026-10-06 14:52:33 +03:00
1 parent 008254e44a
commit de49f93b0b
64 files changed
+9244 -132

No files matched your search

@@ -5223,6 +5223,237 @@ func (s *Server) handleGetSpecializationCatalogRequest(args [0]string, argsEscap
}
}
// handleListMyConsentsRequest handles ListMyConsents operation.
//
// Requires the session cookie of a candidate or an employer account. The subject comes from the
// session, never from a request parameter, so the response holds only the caller's own consents: no
// request can name another account, and records of other accounts are never listed. Returns a page of
// the consent ledger of the account, newest grant first with the identifier as the tie-breaker, with
// cursor pagination.
//
// The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the
// source, and the grant time; the server also stores the hash of exactly the text the subject saw. A
// newer text version of the same purpose is a new record, and the earlier one becomes `superseded`
// without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one
// organization, once; a later grant is a new record. Purposes are independent.
//
// Without `state` the page lists the whole history; `state=active` lists the consents that hold now,
// one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the
// organization with the name its consent text showed (a snapshot that a later rename does not change),
// the selected contact fields, and the invitation with its terms version; it never carries a contact
// value. A c2 record proves the consent to the publication text; the published field set and its
// changes are evidence of the publication history (TASK-088).
//
// Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations
// of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed
// `limit`, `cursor`, or `state` answers 400 validation_failed.
//
// GET /api/v1/me/consents
func (s *Server) handleListMyConsentsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("ListMyConsents"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/me/consents"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyConsentsOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: ListMyConsentsOperation,
ID: "ListMyConsents",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, ListMyConsentsOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeListMyConsentsParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response ListMyConsentsRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: ListMyConsentsOperation,
OperationSummary: "List the consents of the current account with their history.",
OperationID: "ListMyConsents",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "state",
In: "query",
}: params.State,
{
Name: "limit",
In: "query",
}: params.Limit,
{
Name: "cursor",
In: "query",
}: params.Cursor,
},
Raw: r,
}
type (
Request = struct{}
Params = ListMyConsentsParams
Response = ListMyConsentsRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackListMyConsentsParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.ListMyConsents(ctx, params)
return response, err
},
)
} else {
response, err = s.h.ListMyConsents(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeListMyConsentsResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleListMyInvitationsRequest handles ListMyInvitations operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from