feat(org): add organization and membership contract and storage

This commit is contained in:
shira committed 2026-10-06 15:55:29 +03:00
1 parent a0551a34b8
commit bdc5855001
90 files changed
+17545 -480

No files matched your search

@@ -17,20 +17,22 @@ import (
)
var regexMap = map[string]ogenregex.Regexp{
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
"^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"),
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
"^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"),
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^\\S(?:[^\\n\\r]*\\S)?$": ogenregex.MustCompile("^\\S(?:[^\\n\\r]*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
"^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"),
}
var (
// Allocate option closure once.
@@ -1342,6 +1342,263 @@ func (s *Server) handleCreateMySupportCaseRequest(args [0]string, argsEscaped bo
}
}
// handleCreateOrganizationRequest handles CreateOrganization operation.
//
// Requires the session cookie of an employer account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the
// session: the body has no owner, membership, role, verification, or version field, and unknown fields
// fail validation.
//
// The server creates the organization and the owner membership of the caller (role `owner`, state
// `active`) in one transaction, so an organization never exists without its owner. The organization
// starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be
// requested: the creator of a company with a corporate domain, a long description, or many
// representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of
// the server that do not exist yet. Only `name` is required; the rest of the card can be completed
// with UpdateOrganization.
//
// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates
// nothing, so a lost response never creates a second organization. A different body with the same key
// answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
// Two requests with different keys are two organizations; the product may limit the number of
// organizations per account (open question), which would answer 409 `state_conflict` without a change
// of the schema.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409
// idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a
// website that is not an https URL of a host name, `/name` for a name with surrounding whitespace).
// The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
//
// POST /api/v1/organizations
func (s *Server) handleCreateOrganizationRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("CreateOrganization"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.HTTPRouteKey.String("/api/v1/organizations"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), CreateOrganizationOperation,
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: CreateOrganizationOperation,
ID: "CreateOrganization",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, CreateOrganizationOperation, 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
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, CreateOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
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 := decodeCreateOrganizationParams(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
request, rawBody, close, err := s.decodeCreateOrganizationRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response CreateOrganizationRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: CreateOrganizationOperation,
OperationSummary: "Create an organization; the caller becomes its owner.",
OperationID: "CreateOrganization",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "Idempotency-Key",
In: "header",
}: params.IdempotencyKey,
},
Raw: r,
}
type (
Request = *OrganizationCreate
Params = CreateOrganizationParams
Response = CreateOrganizationRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackCreateOrganizationParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.CreateOrganization(ctx, request, params)
return response, err
},
)
} else {
response, err = s.h.CreateOrganization(ctx, request, 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 := encodeCreateOrganizationResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleCreateOrganizationInvitationRequest handles CreateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -4390,6 +4647,224 @@ func (s *Server) handleGetMySupportCaseRequest(args [1]string, argsEscaped bool,
}
}
// handleGetOrganizationRequest handles GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
// holds: it never rises because the profile is complete, because the organization has members, or
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
//
// GET /api/v1/organizations/{org_id}
func (s *Server) handleGetOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetOrganization"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationOperation,
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: GetOrganizationOperation,
ID: "GetOrganization",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationOperation, 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 := decodeGetOrganizationParams(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 GetOrganizationRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: GetOrganizationOperation,
OperationSummary: "Read an organization of which the caller is a member.",
OperationID: "GetOrganization",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "org_id",
In: "path",
}: params.OrgID,
},
Raw: r,
}
type (
Request = struct{}
Params = GetOrganizationParams
Response = GetOrganizationRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackGetOrganizationParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.GetOrganization(ctx, params)
return response, err
},
)
} else {
response, err = s.h.GetOrganization(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 := encodeGetOrganizationResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleGetOrganizationInvitationRequest handles GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -5670,6 +6145,233 @@ func (s *Server) handleListMyInvitationsRequest(args [0]string, argsEscaped bool
}
}
// handleListMyOrganizationsRequest handles ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
// request parameter, so the response holds only the caller's own memberships and no request can name
// another account.
//
// Returns a page of the organizations in which the caller has an `active` membership, newest
// membership first with the organization identifier as the tie-breaker, with cursor pagination. Each
// item names the organization (`OrganizationSummary`) and holds the caller's role and state in it
// (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not
// list its organization, so an organization the caller cannot enter is never named, and one that the
// caller was removed from disappears from the list at once.
//
// The list is the directory of the active organization context. The context is not stored on the
// server: every organization-scoped operation names its organization in the path `org_id`, and the
// server checks that identifier against the caller's active membership on every request, so a switch
// between organizations is a different `org_id` in the client's routes and cannot outlive a revoked
// membership. A client picks the context from this list, may remember the last choice in the browser
// as a convenience, and must read the list again after any answer 404 `not_found` from an organization
// path. An account with several memberships sees all of them here and works in one at a time; the
// rights and the data of the organizations stay separate.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden. An employer account without an organization gets an empty page, which
// tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400
// validation_failed.
//
// GET /api/v1/me/organizations
func (s *Server) handleListMyOrganizationsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("ListMyOrganizations"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/me/organizations"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyOrganizationsOperation,
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: ListMyOrganizationsOperation,
ID: "ListMyOrganizations",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, ListMyOrganizationsOperation, 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 := decodeListMyOrganizationsParams(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 ListMyOrganizationsRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: ListMyOrganizationsOperation,
OperationSummary: "List the organizations available to the current account.",
OperationID: "ListMyOrganizations",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "limit",
In: "query",
}: params.Limit,
{
Name: "cursor",
In: "query",
}: params.Cursor,
},
Raw: r,
}
type (
Request = struct{}
Params = ListMyOrganizationsParams
Response = ListMyOrganizationsRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackListMyOrganizationsParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.ListMyOrganizations(ctx, params)
return response, err
},
)
} else {
response, err = s.h.ListMyOrganizations(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 := encodeListMyOrganizationsResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleListMySupportCasesRequest handles ListMySupportCases operation.
//
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
@@ -8162,6 +8864,269 @@ func (s *Server) handleSubmitMyAssessmentAnswerRequest(args [1]string, argsEscap
}
}
// handleUpdateOrganizationRequest handles UpdateOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
// token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the
// organization (the FR07 matrix gives this to no other role), so a member with another role answers
// 403 forbidden. The role comes from the server-side membership; the body has no organization,
// membership, role, owner, or verification field.
//
// Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch.
// Each field present replaces that field as a whole and an absent field stays unchanged; `contacts`
// and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as
// null become unset; `name`, `contacts`, and `representatives` cannot be null.
//
// The body can change the profile only. The verification level, its basis, the card, the members, and
// every role are not fields of it, and unknown fields fail validation, so the owner can neither raise
// the trust level of the organization nor the rights of anyone by editing the profile; a longer
// description, a verified-looking website, or a new representative leaves the level unchanged. The
// level and the roles change only through processes of the server.
//
// Versions: every committed change creates version `expected_version + 1` and answers 200 with the
// organization. `expected_version` is the `version` the client read; when it is not current, the
// server answers 412 version_conflict and changes nothing, and the client reads the organization again
// and reapplies its edits. The version travels in the body rather than in If-Match because the
// generated client cannot read the ETag response header yet, as for needs. A body that changes nothing
// when applied to the current profile keeps the version and answers 200 with the current organization
// even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a
// change that already succeeded is harmless.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403
// forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer
// such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can
// answer 429 with Retry-After before any check.
//
// PATCH /api/v1/organizations/{org_id}
func (s *Server) handleUpdateOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("UpdateOrganization"),
semconv.HTTPRequestMethodKey.String("PATCH"),
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), UpdateOrganizationOperation,
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: UpdateOrganizationOperation,
ID: "UpdateOrganization",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, UpdateOrganizationOperation, 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
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, UpdateOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
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 := decodeUpdateOrganizationParams(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
request, rawBody, close, err := s.decodeUpdateOrganizationRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response UpdateOrganizationRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: UpdateOrganizationOperation,
OperationSummary: "Change the profile of an organization.",
OperationID: "UpdateOrganization",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "org_id",
In: "path",
}: params.OrgID,
},
Raw: r,
}
type (
Request = *OrganizationUpdate
Params = UpdateOrganizationParams
Response = UpdateOrganizationRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackUpdateOrganizationParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.UpdateOrganization(ctx, request, params)
return response, err
},
)
} else {
response, err = s.h.UpdateOrganization(ctx, request, 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 := encodeUpdateOrganizationResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleUpdateOrganizationInvitationRequest handles UpdateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -29,6 +29,10 @@ type CreateOrganizationNeedRes interface {
createOrganizationNeedRes()
}
type CreateOrganizationRes interface {
createOrganizationRes()
}
type DeclineMyInvitationRes interface {
declineMyInvitationRes()
}
@@ -85,6 +89,10 @@ type GetOrganizationNeedRes interface {
getOrganizationNeedRes()
}
type GetOrganizationRes interface {
getOrganizationRes()
}
type ListMyConsentsRes interface {
listMyConsentsRes()
}
@@ -93,6 +101,10 @@ type ListMyInvitationsRes interface {
listMyInvitationsRes()
}
type ListMyOrganizationsRes interface {
listMyOrganizationsRes()
}
type ListMySupportCasesRes interface {
listMySupportCasesRes()
}
@@ -145,6 +157,10 @@ type UpdateOrganizationNeedRes interface {
updateOrganizationNeedRes()
}
type UpdateOrganizationRes interface {
updateOrganizationRes()
}
type ViewMyInvitationRes interface {
viewMyInvitationRes()
}
File diff suppressed because it is too large. Load diff
@@ -11,6 +11,7 @@ const (
ConfirmEmailOperation OperationName = "ConfirmEmail"
CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt"
CreateMySupportCaseOperation OperationName = "CreateMySupportCase"
CreateOrganizationOperation OperationName = "CreateOrganization"
CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation"
CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed"
DeclineMyInvitationOperation OperationName = "DeclineMyInvitation"
@@ -25,12 +26,14 @@ const (
GetMyInvitationOperation OperationName = "GetMyInvitation"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetMySupportCaseOperation OperationName = "GetMySupportCase"
GetOrganizationOperation OperationName = "GetOrganization"
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
ListMyConsentsOperation OperationName = "ListMyConsents"
ListMyInvitationsOperation OperationName = "ListMyInvitations"
ListMyOrganizationsOperation OperationName = "ListMyOrganizations"
ListMySupportCasesOperation OperationName = "ListMySupportCases"
ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations"
ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds"
@@ -42,6 +45,7 @@ const (
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation"
SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer"
UpdateOrganizationOperation OperationName = "UpdateOrganization"
UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation"
UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed"
ViewMyInvitationOperation OperationName = "ViewMyInvitation"
@@ -503,6 +503,100 @@ func decodeCreateMySupportCaseParams(args [0]string, argsEscaped bool, r *http.R
return params, nil
}
// CreateOrganizationParams is parameters of CreateOrganization operation.
type CreateOrganizationParams struct {
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
// is sent without quotes. The server scopes the key by caller and operation and fingerprints the
// request by method, path, and body.
//
// Stored for 24 hours after the first request and replayed with the same status, headers, and body:
// the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404
// not_found or 409 state_conflict. A replay does not repeat the side effect.
//
// Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for
// the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428
// precondition_required (nothing changed; read the resource again and retry), 422
// idempotency_key_reused, 429, and every 5xx.
//
// Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then
// the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused
// before any other key check; a running request with the same fingerprint returns 409
// idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that
// does the server check If-Match, so a retry of a completed change replays its outcome instead of
// failing on the version it has just changed. After 24 hours the key may be accepted as new.
IdempotencyKey string
}
func unpackCreateOrganizationParams(packed middleware.Parameters) (params CreateOrganizationParams) {
{
key := middleware.ParameterKey{
Name: "Idempotency-Key",
In: "header",
}
params.IdempotencyKey = packed[key].(string)
}
return params
}
func decodeCreateOrganizationParams(args [0]string, argsEscaped bool, r *http.Request) (params CreateOrganizationParams, _ error) {
h := uri.NewHeaderDecoder(r.Header)
// Decode header: Idempotency-Key.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "Idempotency-Key",
Explode: false,
}
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
params.IdempotencyKey = c
return nil
}); err != nil {
return err
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 255,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9._:-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(params.IdempotencyKey)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
} else {
return err
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "Idempotency-Key",
In: "header",
Err: err,
}
}
return params, nil
}
// CreateOrganizationInvitationParams is parameters of CreateOrganizationInvitation operation.
type CreateOrganizationInvitationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -1447,6 +1541,75 @@ func decodeGetMySupportCaseParams(args [1]string, argsEscaped bool, r *http.Requ
return params, nil
}
// GetOrganizationParams is parameters of GetOrganization operation.
type GetOrganizationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
// this organization, checked by the server on every request; the identifier itself grants nothing. An
// organization without such a membership and an unknown identifier both answer 404 not_found, so
// organizations cannot be enumerated.
OrgID uuid.UUID
}
func unpackGetOrganizationParams(packed middleware.Parameters) (params GetOrganizationParams) {
{
key := middleware.ParameterKey{
Name: "org_id",
In: "path",
}
params.OrgID = packed[key].(uuid.UUID)
}
return params
}
func decodeGetOrganizationParams(args [1]string, argsEscaped bool, r *http.Request) (params GetOrganizationParams, _ error) {
// Decode path: org_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "org_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.OrgID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "org_id",
In: "path",
Err: err,
}
}
return params, nil
}
// GetOrganizationInvitationParams is parameters of GetOrganizationInvitation operation.
type GetOrganizationInvitationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -2238,6 +2401,182 @@ func decodeListMyInvitationsParams(args [0]string, argsEscaped bool, r *http.Req
return params, nil
}
// ListMyOrganizationsParams is parameters of ListMyOrganizations operation.
type ListMyOrganizationsParams struct {
// Maximum number of items in the page. The server may return fewer items even when more remain; use
// `page.has_more` to detect the end.
Limit OptInt32 `json:",omitempty,omitzero"`
// Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the
// first page. A malformed or foreign cursor returns 400 with code validation_failed.
Cursor OptString `json:",omitempty,omitzero"`
}
func unpackListMyOrganizationsParams(packed middleware.Parameters) (params ListMyOrganizationsParams) {
{
key := middleware.ParameterKey{
Name: "limit",
In: "query",
}
if v, ok := packed[key]; ok {
params.Limit = v.(OptInt32)
}
}
{
key := middleware.ParameterKey{
Name: "cursor",
In: "query",
}
if v, ok := packed[key]; ok {
params.Cursor = v.(OptString)
}
}
return params
}
func decodeListMyOrganizationsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyOrganizationsParams, _ error) {
q := uri.NewQueryDecoder(r.URL.Query())
// Set default value for query: limit.
{
val := int32(20)
params.Limit.SetTo(val)
}
// Decode query: limit.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "limit",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotLimitVal int32
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt32(val)
if err != nil {
return err
}
paramsDotLimitVal = c
return nil
}(); err != nil {
return err
}
params.Limit.SetTo(paramsDotLimitVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Limit.Get(); ok {
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 100,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(value)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "limit",
In: "query",
Err: err,
}
}
// Decode query: cursor.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "cursor",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotCursorVal string
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
paramsDotCursorVal = c
return nil
}(); err != nil {
return err
}
params.Cursor.SetTo(paramsDotCursorVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Cursor.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 512,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "cursor",
In: "query",
Err: err,
}
}
return params, nil
}
// ListMySupportCasesParams is parameters of ListMySupportCases operation.
type ListMySupportCasesParams struct {
// Maximum number of items in the page. The server may return fewer items even when more remain; use
@@ -3535,6 +3874,75 @@ func decodeSubmitMyAssessmentAnswerParams(args [1]string, argsEscaped bool, r *h
return params, nil
}
// UpdateOrganizationParams is parameters of UpdateOrganization operation.
type UpdateOrganizationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
// this organization, checked by the server on every request; the identifier itself grants nothing. An
// organization without such a membership and an unknown identifier both answer 404 not_found, so
// organizations cannot be enumerated.
OrgID uuid.UUID
}
func unpackUpdateOrganizationParams(packed middleware.Parameters) (params UpdateOrganizationParams) {
{
key := middleware.ParameterKey{
Name: "org_id",
In: "path",
}
params.OrgID = packed[key].(uuid.UUID)
}
return params
}
func decodeUpdateOrganizationParams(args [1]string, argsEscaped bool, r *http.Request) (params UpdateOrganizationParams, _ error) {
// Decode path: org_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "org_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.OrgID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "org_id",
In: "path",
Err: err,
}
}
return params, nil
}
// UpdateOrganizationInvitationParams is parameters of UpdateOrganizationInvitation operation.
type UpdateOrganizationInvitationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -409,6 +409,85 @@ func (s *Server) decodeCreateMySupportCaseRequest(r *http.Request) (
}
}
func (s *Server) decodeCreateOrganizationRequest(r *http.Request) (
req *OrganizationCreate,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request OrganizationCreate
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeCreateOrganizationInvitationRequest(r *http.Request) (
req *OrganizationInvitationCreate,
rawBody []byte,
@@ -1278,6 +1357,85 @@ func (s *Server) decodeSubmitMyAssessmentAnswerRequest(r *http.Request) (
}
}
func (s *Server) decodeUpdateOrganizationRequest(r *http.Request) (
req *OrganizationUpdate,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request OrganizationUpdate
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeUpdateOrganizationInvitationRequest(r *http.Request) (
req *OrganizationInvitationUpdate,
rawBody []byte,
@@ -657,6 +657,133 @@ func encodeCreateMySupportCaseResponse(response CreateMySupportCaseRes, w http.R
}
}
func encodeCreateOrganizationResponse(response CreateOrganizationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(201)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationConflict:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(409)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationUnprocessableEntity:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(422)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeCreateOrganizationInvitationResponse(response CreateOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
@@ -1769,6 +1896,89 @@ func encodeGetMySupportCaseResponse(response GetMySupportCaseRes, w http.Respons
}
}
func encodeGetOrganizationResponse(response GetOrganizationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetOrganizationInvitationResponse(response GetOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
@@ -2161,6 +2371,77 @@ func encodeListMyInvitationsResponse(response ListMyInvitationsRes, w http.Respo
}
}
func encodeListMyOrganizationsResponse(response ListMyOrganizationsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *MyOrganizationListHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyOrganizationsBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyOrganizationsUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyOrganizationsForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeListMySupportCasesResponse(response ListMySupportCasesRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *SupportCaseListHeaders:
@@ -3282,6 +3563,133 @@ func encodeSubmitMyAssessmentAnswerResponse(response SubmitMyAssessmentAnswerRes
}
}
func encodeUpdateOrganizationResponse(response UpdateOrganizationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationPreconditionFailed:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(412)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeUpdateOrganizationInvitationResponse(response UpdateOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -60,6 +60,7 @@ var operationRolesSessionCookie = map[string][]string{
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
@@ -72,11 +73,13 @@ var operationRolesSessionCookie = map[string][]string{
GetMyInvitationOperation: []string{},
GetMyQuestionnaireOperation: []string{},
GetMySupportCaseOperation: []string{},
GetOrganizationOperation: []string{},
GetOrganizationInvitationOperation: []string{},
GetOrganizationInvitationContactsOperation: []string{},
GetOrganizationNeedOperation: []string{},
ListMyConsentsOperation: []string{},
ListMyInvitationsOperation: []string{},
ListMyOrganizationsOperation: []string{},
ListMySupportCasesOperation: []string{},
ListOrganizationInvitationsOperation: []string{},
ListOrganizationNeedsOperation: []string{},
@@ -85,6 +88,7 @@ var operationRolesSessionCookie = map[string][]string{
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
@@ -118,6 +122,7 @@ var operationRolesSessionCsrf = map[string][]string{
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
@@ -127,6 +132,7 @@ var operationRolesSessionCsrf = map[string][]string{
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
@@ -253,6 +253,36 @@ type Handler interface {
//
// POST /api/v1/me/support-cases
CreateMySupportCase(ctx context.Context, req SupportCaseCreate, params CreateMySupportCaseParams) (CreateMySupportCaseRes, error)
// CreateOrganization implements CreateOrganization operation.
//
// Requires the session cookie of an employer account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the
// session: the body has no owner, membership, role, verification, or version field, and unknown fields
// fail validation.
//
// The server creates the organization and the owner membership of the caller (role `owner`, state
// `active`) in one transaction, so an organization never exists without its owner. The organization
// starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be
// requested: the creator of a company with a corporate domain, a long description, or many
// representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of
// the server that do not exist yet. Only `name` is required; the rest of the card can be completed
// with UpdateOrganization.
//
// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates
// nothing, so a lost response never creates a second organization. A different body with the same key
// answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
// Two requests with different keys are two organizations; the product may limit the number of
// organizations per account (open question), which would answer 409 `state_conflict` without a change
// of the schema.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409
// idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a
// website that is not an https URL of a host name, `/name` for a name with surrounding whitespace).
// The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
//
// POST /api/v1/organizations
CreateOrganization(ctx context.Context, req *OrganizationCreate, params CreateOrganizationParams) (CreateOrganizationRes, error)
// CreateOrganizationInvitation implements CreateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -608,6 +638,30 @@ type Handler interface {
//
// GET /api/v1/me/support-cases/{case_id}
GetMySupportCase(ctx context.Context, params GetMySupportCaseParams) (GetMySupportCaseRes, error)
// GetOrganization implements GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
// holds: it never rises because the profile is complete, because the organization has members, or
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
//
// GET /api/v1/organizations/{org_id}
GetOrganization(ctx context.Context, params GetOrganizationParams) (GetOrganizationRes, error)
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -765,6 +819,35 @@ type Handler interface {
//
// GET /api/v1/me/invitations
ListMyInvitations(ctx context.Context, params ListMyInvitationsParams) (ListMyInvitationsRes, error)
// ListMyOrganizations implements ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
// request parameter, so the response holds only the caller's own memberships and no request can name
// another account.
//
// Returns a page of the organizations in which the caller has an `active` membership, newest
// membership first with the organization identifier as the tie-breaker, with cursor pagination. Each
// item names the organization (`OrganizationSummary`) and holds the caller's role and state in it
// (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not
// list its organization, so an organization the caller cannot enter is never named, and one that the
// caller was removed from disappears from the list at once.
//
// The list is the directory of the active organization context. The context is not stored on the
// server: every organization-scoped operation names its organization in the path `org_id`, and the
// server checks that identifier against the caller's active membership on every request, so a switch
// between organizations is a different `org_id` in the client's routes and cannot outlive a revoked
// membership. A client picks the context from this list, may remember the last choice in the browser
// as a convenience, and must read the list again after any answer 404 `not_found` from an organization
// path. An account with several memberships sees all of them here and works in one at a time; the
// rights and the data of the organizations stay separate.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden. An employer account without an organization gets an empty page, which
// tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400
// validation_failed.
//
// GET /api/v1/me/organizations
ListMyOrganizations(ctx context.Context, params ListMyOrganizationsParams) (ListMyOrganizationsRes, error)
// ListMySupportCases implements ListMySupportCases operation.
//
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
@@ -1086,6 +1169,42 @@ type Handler interface {
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/answers
SubmitMyAssessmentAnswer(ctx context.Context, req *AssessmentAnswerSubmission, params SubmitMyAssessmentAnswerParams) (SubmitMyAssessmentAnswerRes, error)
// UpdateOrganization implements UpdateOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
// token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the
// organization (the FR07 matrix gives this to no other role), so a member with another role answers
// 403 forbidden. The role comes from the server-side membership; the body has no organization,
// membership, role, owner, or verification field.
//
// Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch.
// Each field present replaces that field as a whole and an absent field stays unchanged; `contacts`
// and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as
// null become unset; `name`, `contacts`, and `representatives` cannot be null.
//
// The body can change the profile only. The verification level, its basis, the card, the members, and
// every role are not fields of it, and unknown fields fail validation, so the owner can neither raise
// the trust level of the organization nor the rights of anyone by editing the profile; a longer
// description, a verified-looking website, or a new representative leaves the level unchanged. The
// level and the roles change only through processes of the server.
//
// Versions: every committed change creates version `expected_version + 1` and answers 200 with the
// organization. `expected_version` is the `version` the client read; when it is not current, the
// server answers 412 version_conflict and changes nothing, and the client reads the organization again
// and reapplies its edits. The version travels in the body rather than in If-Match because the
// generated client cannot read the ETag response header yet, as for needs. A body that changes nothing
// when applied to the current profile keeps the version and answers 200 with the current organization
// even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a
// change that already succeeded is harmless.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403
// forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer
// such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can
// answer 429 with Retry-After before any check.
//
// PATCH /api/v1/organizations/{org_id}
UpdateOrganization(ctx context.Context, req *OrganizationUpdate, params UpdateOrganizationParams) (UpdateOrganizationRes, error)
// UpdateOrganizationInvitation implements UpdateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -273,6 +273,39 @@ func (UnimplementedHandler) CreateMySupportCase(ctx context.Context, req Support
return r, ht.ErrNotImplemented
}
// CreateOrganization implements CreateOrganization operation.
//
// Requires the session cookie of an employer account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the
// session: the body has no owner, membership, role, verification, or version field, and unknown fields
// fail validation.
//
// The server creates the organization and the owner membership of the caller (role `owner`, state
// `active`) in one transaction, so an organization never exists without its owner. The organization
// starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be
// requested: the creator of a company with a corporate domain, a long description, or many
// representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of
// the server that do not exist yet. Only `name` is required; the rest of the card can be completed
// with UpdateOrganization.
//
// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates
// nothing, so a lost response never creates a second organization. A different body with the same key
// answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
// Two requests with different keys are two organizations; the product may limit the number of
// organizations per account (open question), which would answer 409 `state_conflict` without a change
// of the schema.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409
// idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a
// website that is not an https URL of a host name, `/name` for a name with surrounding whitespace).
// The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
//
// POST /api/v1/organizations
func (UnimplementedHandler) CreateOrganization(ctx context.Context, req *OrganizationCreate, params CreateOrganizationParams) (r CreateOrganizationRes, _ error) {
return r, ht.ErrNotImplemented
}
// CreateOrganizationInvitation implements CreateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -670,6 +703,33 @@ func (UnimplementedHandler) GetMySupportCase(ctx context.Context, params GetMySu
return r, ht.ErrNotImplemented
}
// GetOrganization implements GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
// holds: it never rises because the profile is complete, because the organization has members, or
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
//
// GET /api/v1/organizations/{org_id}
func (UnimplementedHandler) GetOrganization(ctx context.Context, params GetOrganizationParams) (r GetOrganizationRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -845,6 +905,38 @@ func (UnimplementedHandler) ListMyInvitations(ctx context.Context, params ListMy
return r, ht.ErrNotImplemented
}
// ListMyOrganizations implements ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
// request parameter, so the response holds only the caller's own memberships and no request can name
// another account.
//
// Returns a page of the organizations in which the caller has an `active` membership, newest
// membership first with the organization identifier as the tie-breaker, with cursor pagination. Each
// item names the organization (`OrganizationSummary`) and holds the caller's role and state in it
// (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not
// list its organization, so an organization the caller cannot enter is never named, and one that the
// caller was removed from disappears from the list at once.
//
// The list is the directory of the active organization context. The context is not stored on the
// server: every organization-scoped operation names its organization in the path `org_id`, and the
// server checks that identifier against the caller's active membership on every request, so a switch
// between organizations is a different `org_id` in the client's routes and cannot outlive a revoked
// membership. A client picks the context from this list, may remember the last choice in the browser
// as a convenience, and must read the list again after any answer 404 `not_found` from an organization
// path. An account with several memberships sees all of them here and works in one at a time; the
// rights and the data of the organizations stay separate.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden. An employer account without an organization gets an empty page, which
// tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400
// validation_failed.
//
// GET /api/v1/me/organizations
func (UnimplementedHandler) ListMyOrganizations(ctx context.Context, params ListMyOrganizationsParams) (r ListMyOrganizationsRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListMySupportCases implements ListMySupportCases operation.
//
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
@@ -1199,6 +1291,45 @@ func (UnimplementedHandler) SubmitMyAssessmentAnswer(ctx context.Context, req *A
return r, ht.ErrNotImplemented
}
// UpdateOrganization implements UpdateOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
// token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the
// organization (the FR07 matrix gives this to no other role), so a member with another role answers
// 403 forbidden. The role comes from the server-side membership; the body has no organization,
// membership, role, owner, or verification field.
//
// Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch.
// Each field present replaces that field as a whole and an absent field stays unchanged; `contacts`
// and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as
// null become unset; `name`, `contacts`, and `representatives` cannot be null.
//
// The body can change the profile only. The verification level, its basis, the card, the members, and
// every role are not fields of it, and unknown fields fail validation, so the owner can neither raise
// the trust level of the organization nor the rights of anyone by editing the profile; a longer
// description, a verified-looking website, or a new representative leaves the level unchanged. The
// level and the roles change only through processes of the server.
//
// Versions: every committed change creates version `expected_version + 1` and answers 200 with the
// organization. `expected_version` is the `version` the client read; when it is not current, the
// server answers 412 version_conflict and changes nothing, and the client reads the organization again
// and reapplies its edits. The version travels in the body rather than in If-Match because the
// generated client cannot read the ETag response header yet, as for needs. A body that changes nothing
// when applied to the current profile keeps the version and answers 200 with the current organization
// even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a
// change that already succeeded is harmless.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403
// forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer
// such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can
// answer 429 with Retry-After before any check.
//
// PATCH /api/v1/organizations/{org_id}
func (UnimplementedHandler) UpdateOrganization(ctx context.Context, req *OrganizationUpdate, params UpdateOrganizationParams) (r UpdateOrganizationRes, _ error) {
return r, ht.ErrNotImplemented
}
// UpdateOrganizationInvitation implements UpdateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,576 @@
package httpadapter
import (
"context"
"log/slog"
"net/http"
"reflect"
"slices"
"strings"
"testing"
"github.com/ogen-go/ogen"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
)
// Organization request fixtures shared by the organization tests.
const (
myOrganizationsPath = "/api/v1/me/organizations"
organizationsPath = "/api/v1/organizations"
organizationPath = organizationsPath + "/01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"
validOrganizationContacts = `{"website":"https://payments.example.com","email":"careers@payments.example.com","phone":"+74950000000","telegram":"@payments_careers"}`
emptyOrganizationContacts = `{"website":null,"email":null,"phone":null,"telegram":null}`
)
// organizationBody builds a JSON object from the given members.
func organizationBody(members ...string) string {
return "{" + strings.Join(members, ",") + "}"
}
// The schemas alone must accept the profile a company may send and reject
// what no request may carry: a role, an owner, a verification level or its
// basis, the members, the card, a version, or an identifier. Security accepts
// the session here, so the request reaches validation; a valid request then
// answers 501 until the operations are implemented. The rules that need
// storage, such as the website host or the version, pass the schema and are
// checked by the server.
func TestOrganizationSchemaValidationPrecedesImplementation(t *testing.T) {
session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
create := func(body string) identityRequest {
return identityRequest{method: http.MethodPost, path: organizationsPath, body: body, headers: command}
}
update := func(members ...string) identityRequest {
return identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(append([]string{`"expected_version":1`}, members...)...), headers: session}
}
forbiddenFields := []string{
`"role":"owner"`,
`"owner_id":"01928f7a-0000-7000-8000-00000000c0de"`,
`"verification_level":"e1"`,
`"verification":{"level":"e2","basis":"manual_review","changed_at":"2026-10-06T09:00:00Z"}`,
`"verification_basis":"corporate_domain"`,
`"members":[{"user_id":"01928f7a-0000-7000-8000-00000000c0de","role":"owner"}]`,
`"membership":{"organization_id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","role":"owner","state":"active","joined_at":"2026-10-06T09:00:00Z"}`,
`"candidate_card":{}`,
`"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"`,
`"version":3`,
`"created_at":"2026-10-06T09:00:00Z"`,
}
type expectation struct {
name string
request identityRequest
location api.ProblemFieldLocation
pointer string
code string
}
tests := make([]expectation, 0, 36+2*len(forbiddenFields))
tests = append(tests, []expectation{
{
name: "list",
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?limit=20", headers: session},
},
{
name: "list with a limit above the maximum",
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?limit=101", headers: session},
location: api.ProblemFieldLocationQuery, pointer: "/limit", code: "invalid",
},
{
name: "list with a malformed cursor",
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?cursor=not%20a%20cursor", headers: session},
location: api.ProblemFieldLocationQuery, pointer: "/cursor", code: "invalid",
},
{
name: "create with a name only",
request: create(organizationBody(`"name":"ООО Пример Платежи"`)),
},
{
name: "create with a complete card",
request: create(organizationBody(
`"name":"ООО Пример Платежи"`,
`"description":"Платежный сервис.\nСобственное ядро."`,
`"sphere":"Платежи и финансовые сервисы"`,
`"contacts":`+validOrganizationContacts,
`"representatives":[{"name":"Анна Тестова","job_title":"Руководитель по подбору"}]`,
)),
},
{
name: "create with an explicit null description and sphere",
request: create(organizationBody(`"name":"ООО Пример"`, `"description":null`, `"sphere":null`, `"contacts":`+emptyOrganizationContacts, `"representatives":[]`)),
},
{
// A domain rule of the server: the schema accepts any https
// string without credentials, and the host rules come after it.
name: "create with a website that has a port",
request: create(organizationBody(`"name":"ООО Пример"`, `"contacts":{"website":"https://payments.example.com:8443","email":null,"phone":null,"telegram":null}`)),
},
{
name: "create without a name",
request: create(organizationBody(`"sphere":"Платежи"`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "required",
},
{
name: "create without an Idempotency-Key",
request: identityRequest{method: http.MethodPost, path: organizationsPath, body: organizationBody(`"name":"ООО Пример"`), headers: session},
location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required",
},
{
name: "create with an empty name",
request: create(organizationBody(`"name":""`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "create with a name over 200 characters",
request: create(organizationBody(`"name":"` + strings.Repeat("я", 201) + `"`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "create with a name that has a leading space",
request: create(organizationBody(`"name":" ООО"`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "create with a name that has a line break",
request: create(organizationBody(`"name":"ООО\nПример"`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "create with a sphere that has a trailing space",
request: create(organizationBody(`"name":"ООО"`, `"sphere":"Платежи "`)),
location: api.ProblemFieldLocationBody, pointer: "/sphere", code: "invalid",
},
{
name: "create with an empty description",
request: create(organizationBody(`"name":"ООО"`, `"description":""`)),
location: api.ProblemFieldLocationBody, pointer: "/description", code: "invalid",
},
{
name: "create with contacts that omit a field",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/telegram", code: "required",
},
{
name: "create with a personal contact kind",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null,"telegram":null,"home_address":"ул. Тестовая"}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts", code: "invalid",
},
{
name: "create with an http website",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":"http://payments.example.com","email":null,"phone":null,"telegram":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/website", code: "invalid",
},
{
name: "create with a website that has credentials",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":"https://user:secret@payments.example.com","email":null,"phone":null,"telegram":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/website", code: "invalid",
},
{
name: "create with a phone that is not E.164",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":"8 495 000-00-00","telegram":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/phone", code: "invalid",
},
{
name: "create with a Telegram username without the at sign",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null,"telegram":"payments_careers"}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/telegram", code: "invalid",
},
{
name: "create with an email that is not an address",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":"careers","phone":null,"telegram":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/email", code: "invalid",
},
{
name: "create with eleven representatives",
request: create(organizationBody(`"name":"ООО"`, `"representatives":[`+
strings.TrimSuffix(strings.Repeat(`{"name":"Имя","job_title":"Должность"},`, 11), ",")+`]`)),
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
},
{
// A failure inside an array element during decoding reports the
// pointer of the array, because jx reports no element index.
name: "create with a representative that has no job title",
request: create(organizationBody(`"name":"ООО"`, `"representatives":[{"name":"Анна Тестова"}]`)),
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
},
{
name: "create with a representative contact",
request: create(organizationBody(`"name":"ООО"`, `"representatives":[{"name":"Анна Тестова","job_title":"HR","email":"anna@example.com"}]`)),
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
},
{
name: "update with the version only",
request: update(),
},
{
name: "update of the profile with explicit nulls",
request: update(`"description":null`, `"sphere":null`),
},
{
name: "update of the contacts and representatives as a whole",
request: update(`"contacts":`+emptyOrganizationContacts, `"representatives":[]`),
},
{
name: "update without expected_version",
request: identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"name":"ООО Новое"`), headers: session},
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required",
},
{
name: "update with expected_version zero",
request: identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"expected_version":0`), headers: session},
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "invalid",
},
{
name: "update with a null name",
request: update(`"name":null`),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "update with null representatives",
request: update(`"representatives":null`),
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
},
{
name: "update with null contacts",
request: update(`"contacts":null`),
location: api.ProblemFieldLocationBody, pointer: "/contacts", code: "invalid",
},
{
name: "read",
request: identityRequest{method: http.MethodGet, path: organizationPath, headers: session},
},
{
name: "read an organization identifier that is not a UUID",
request: identityRequest{method: http.MethodGet, path: organizationsPath + "/acme", headers: session},
location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid",
},
{
name: "update an organization identifier that is not a UUID",
request: identityRequest{method: http.MethodPatch, path: organizationsPath + "/acme", body: organizationBody(`"expected_version":1`), headers: session},
location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid",
},
}...)
// No request of either command may carry a right or a trust level, each
// one alone, as a whole-body rejection of an unknown field.
for _, field := range forbiddenFields {
tests = append(tests,
expectation{
name: "create with the forbidden field " + strings.SplitN(field, ":", 2)[0],
request: create(organizationBody(`"name":"ООО Пример"`, field)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
expectation{
name: "update with the forbidden field " + strings.SplitN(field, ":", 2)[0],
request: update(field),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
)
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
response := serveIdentityRequest(t, router, test.request)
switch test.code {
case "":
requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented)
default:
body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed)
want := api.ProblemFieldError{In: test.location, Pointer: test.pointer, Code: test.code}
for _, field := range body.Errors {
if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code {
return
}
}
t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want)
}
})
}
}
// Every organization operation requires an employer session; DenyAllSecurity
// grants none, with or without a cookie and a CSRF token, and no request can
// name another account.
func TestOrganizationAccessBeforeImplementation(t *testing.T) {
session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
for _, test := range []identityRequest{
{method: http.MethodGet, path: myOrganizationsPath},
{method: http.MethodGet, path: myOrganizationsPath, headers: map[string]string{"Cookie": testSessionCookie}},
{method: http.MethodGet, path: myOrganizationsPath + "?user_id=01928f7a-0000-7000-8000-00000000c0de", headers: map[string]string{"Cookie": testSessionCookie}},
{method: http.MethodPost, path: organizationsPath, body: organizationBody(`"name":"ООО Пример"`), headers: command},
{method: http.MethodGet, path: organizationPath},
{method: http.MethodGet, path: organizationPath, headers: map[string]string{"Cookie": testSessionCookie}},
{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"expected_version":1`, `"name":"ООО Новое"`), headers: session},
} {
t.Run(test.method+" "+test.path, func(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
requireProblem(t, serveIdentityRequest(t, router, test), http.StatusUnauthorized, api.ProblemCodeUnauthenticated)
})
}
}
// A role and a verification level never travel in the company DTOs: not in
// the response a member reads, not in the create or the update body. The
// role lives in OrganizationMembership, which a client cannot send, and the
// level in OrganizationVerification, which only the response carries.
func TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests(t *testing.T) {
raising := []string{
"role", "roles", "verification", "verification_level", "verification_basis", "level", "basis", "trust_level",
"owner", "owner_id", "members", "membership", "user_id", "account_id", "permissions", "e0", "e1", "e2", "e3",
}
for _, dto := range []any{api.Organization{}, api.OrganizationCreate{}, api.OrganizationUpdate{}, api.CandidateOrganizationCard{}, api.OrganizationContactChannels{}, api.OrganizationRepresentative{}} {
typ := reflect.TypeOf(dto)
for i := range typ.NumField() {
name, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",")
isVerificationReadModel := (typ == reflect.TypeFor[api.Organization]() && name == "verification") ||
(typ == reflect.TypeFor[api.CandidateOrganizationCard]() && name == "verification_level")
for _, field := range raising {
if name == field && !isVerificationReadModel {
t.Errorf("%s exposes the field %q", typ.Name(), name)
}
}
}
}
// The two request DTOs have no verification field at all, not even the
// read-only ones of the response.
for _, dto := range []any{api.OrganizationCreate{}, api.OrganizationUpdate{}} {
assertNoJSONFields(t, dto, []string{"verification", "verification_level", "candidate_card", "id", "version", "created_at", "updated_at"})
}
// The profile fields of a request are the whole editable surface.
for _, profile := range []struct {
dto any
want []string
}{
{api.OrganizationCreate{}, []string{"name", "description", "sphere", "contacts", "representatives"}},
{api.OrganizationUpdate{}, []string{"expected_version", "name", "description", "sphere", "contacts", "representatives"}},
} {
typ, want := reflect.TypeOf(profile.dto), profile.want
got := make([]string, 0, typ.NumField())
for i := range typ.NumField() {
name, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",")
got = append(got, name)
}
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Errorf("%s fields = %v, want exactly %v", typ.Name(), got, want)
}
}
// The candidate's card holds neither a member, a role, nor the ground
// of the verification.
assertNoJSONFields(t, api.CandidateOrganizationCard{}, []string{"role", "membership", "members", "verification", "basis", "version", "created_at", "updated_at", "user_id"})
// The caller's own membership is the only place of a role, and it names
// no account.
assertNoJSONFields(t, api.OrganizationMembership{}, []string{"user_id", "account_id", "email"})
// The list takes only the page, so no parameter names another account.
params := reflect.TypeFor[api.ListMyOrganizationsParams]()
names := make([]string, 0, params.NumField())
for i := range params.NumField() {
names = append(names, params.Field(i).Name)
}
if got := strings.Join(names, ","); got != "Limit,Cursor" {
t.Fatalf("ListMyOrganizationsParams fields = %s, want only the page", got)
}
}
// An update separates an absent list (unchanged) from an empty one (replaced
// by an empty list) by nil, and null is not a list or an object.
func TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart(t *testing.T) {
var empty api.OrganizationUpdate
if err := empty.UnmarshalJSON([]byte(`{"expected_version":1,"representatives":[]}`)); err != nil {
t.Fatalf("decode an empty list: %v", err)
}
if empty.Representatives == nil || len(empty.Representatives) != 0 {
t.Fatalf("representatives = %#v, want a non-nil empty slice", empty.Representatives)
}
var absent api.OrganizationUpdate
if err := absent.UnmarshalJSON([]byte(`{"expected_version":1}`)); err != nil {
t.Fatalf("decode an absent list: %v", err)
}
if absent.Representatives != nil || absent.Name.IsSet() || absent.Contacts.IsSet() || absent.Description.IsSet() || absent.Sphere.IsSet() {
t.Fatal("absent fields are set, want unset")
}
var cleared api.OrganizationUpdate
if err := cleared.UnmarshalJSON([]byte(`{"expected_version":1,"description":null,"sphere":"Платежи"}`)); err != nil {
t.Fatalf("decode a null description: %v", err)
}
if !cleared.Description.IsSet() || !cleared.Description.IsNull() || !cleared.Sphere.IsSet() || cleared.Sphere.IsNull() {
t.Fatal("description sent as null is not a set null, or the sphere is not a value")
}
for _, body := range []string{
`{"expected_version":1,"representatives":null}`,
`{"expected_version":1,"name":null}`,
`{"expected_version":1,"contacts":null}`,
} {
var null api.OrganizationUpdate
if err := null.UnmarshalJSON([]byte(body)); err == nil {
t.Fatalf("decode %s succeeded, want an error", body)
}
}
}
// The representatives of the candidate card are optional and nullable: absent
// or null means that they are not published.
func TestCandidateOrganizationCardRepresentativesAreOptional(t *testing.T) {
const base = `"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","name":"ООО Пример","description":null,"sphere":null,"contacts":` + emptyOrganizationContacts + `,"verification_level":"e0"`
for name, body := range map[string]string{
"absent": "{" + base + "}",
"null": "{" + base + `,"representatives":null}`,
"empty": "{" + base + `,"representatives":[]}`,
} {
var card api.CandidateOrganizationCard
if err := card.UnmarshalJSON([]byte(body)); err != nil {
t.Fatalf("decode a card with %s representatives: %v", name, err)
}
if err := card.Validate(); err != nil {
t.Fatalf("validate a card with %s representatives: %v", name, err)
}
}
var withoutContacts api.CandidateOrganizationCard
if err := withoutContacts.UnmarshalJSON([]byte(`{"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","name":"ООО","description":null,"sphere":null,"verification_level":"e0"}`)); err == nil {
t.Fatal("decode a card without contacts succeeded, want an error")
}
}
// The documented examples are valid values of the generated types, and the
// organizations they show never claim a level above e0 on their own.
func TestOrganizationExamplesAreValidResponsesAndNeverRaiseTheLevel(t *testing.T) {
for _, name := range []string{"OrganizationNameOnly", "OrganizationCompleteCard"} {
var organization api.Organization
if err := organization.UnmarshalJSON(supportCaseExample(t, name)); err != nil {
t.Fatalf("decode the %s example: %v", name, err)
}
if err := organization.Validate(); err != nil {
t.Fatalf("validate the %s example: %v", name, err)
}
if organization.Verification.Level != api.OrganizationVerificationLevelE0 || organization.Verification.Basis != api.OrganizationVerificationBasisConfirmedEmail ||
organization.CandidateCard.VerificationLevel != api.OrganizationVerificationLevelE0 {
t.Fatalf("%s example verification = %+v, want e0 on the confirmed email", name, organization.Verification)
}
if organization.CandidateCard.ID != organization.ID || organization.CandidateCard.Name != organization.Name {
t.Fatalf("%s example card does not repeat the profile", name)
}
}
var page api.MyOrganizationList
if err := page.UnmarshalJSON(supportCaseExample(t, "MyOrganizationListPage")); err != nil {
t.Fatalf("decode the MyOrganizationListPage example: %v", err)
}
if err := page.Validate(); err != nil {
t.Fatalf("validate the MyOrganizationListPage example: %v", err)
}
for _, item := range page.Items {
if item.Membership.State != api.MembershipStateActive || item.Membership.OrganizationID != item.Organization.ID {
t.Fatalf("listed item %+v, want an active membership of the listed organization", item)
}
}
for _, name := range []string{"OrganizationCreateNameOnly", "OrganizationCreateCompleteCard"} {
var create api.OrganizationCreate
if err := create.UnmarshalJSON(supportCaseExample(t, name)); err != nil {
t.Fatalf("decode the %s example: %v", name, err)
}
if err := create.Validate(); err != nil {
t.Fatalf("validate the %s example: %v", name, err)
}
}
var update api.OrganizationUpdate
if err := update.UnmarshalJSON(supportCaseExample(t, "OrganizationUpdateCompleteCard")); err != nil {
t.Fatalf("decode the OrganizationUpdateCompleteCard example: %v", err)
}
if err := update.Validate(); err != nil {
t.Fatalf("validate the OrganizationUpdateCompleteCard example: %v", err)
}
}
// The contract enums list every level, basis, role, and state of the PRD now,
// so adding one later is not a contract change. At the contract level, the
// profile bodies are closed objects without a role or a level, and no
// operation sets the verification level or a role.
func TestOrganizationContractFollowsThePRD(t *testing.T) {
spec := parsePublicContract(t)
for name, want := range map[string][]string{
"OrganizationVerificationLevel": {"e0", "e1", "e2", "e3"},
"OrganizationVerificationBasis": {"confirmed_email", "corporate_domain", "requisites_and_authority", "manual_review", "partner_status"},
"OrganizationRole": {"owner", "recruiter", "hiring_manager", "technical_expert"},
"MembershipState": {"active", "suspended", "removed", "left"},
} {
if got := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name})); !slices.Equal(got, want) {
t.Errorf("%s = %v, want %v", name, got, want)
}
}
// The requests are closed objects whose properties are the profile.
for name, want := range map[string][]string{
"OrganizationCreate": {"name", "description", "sphere", "contacts", "representatives"},
"OrganizationUpdate": {"expected_version", "name", "description", "sphere", "contacts", "representatives"},
} {
schema := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name})
if schema.AdditionalProperties == nil || schema.AdditionalProperties.Bool == nil || *schema.AdditionalProperties.Bool {
t.Errorf("%s accepts unknown fields", name)
}
got := make([]string, 0, len(schema.Properties))
for _, property := range schema.Properties {
got = append(got, property.Name)
}
slices.Sort(got)
sorted := slices.Clone(want)
slices.Sort(sorted)
if !slices.Equal(got, sorted) {
t.Errorf("%s properties = %v, want %v", name, got, sorted)
}
}
update := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/OrganizationUpdate"})
if !slices.Contains(update.Required, "expected_version") {
t.Error("OrganizationUpdate does not require expected_version")
}
create := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/OrganizationCreate"})
if !slices.Equal(create.Required, []string{"name"}) {
t.Errorf("OrganizationCreate required = %v, want only the name", create.Required)
}
// Writing needs the CSRF token, and creating needs an Idempotency-Key.
for _, id := range []string{"CreateOrganization", "UpdateOrganization"} {
operation := operationByID(t, spec, id)
if len(operation.Security) != 1 {
t.Fatalf("%s security = %v, want one requirement", id, operation.Security)
}
if _, ok := operation.Security[0][sessionCSRFScheme]; !ok {
t.Errorf("%s does not require the CSRF token", id)
}
}
if !slices.ContainsFunc(operationByID(t, spec, "CreateOrganization").Parameters, func(parameter *ogen.Parameter) bool {
return parameter.Ref == "#/components/parameters/IdempotencyKey"
}) {
t.Error("CreateOrganization does not require an Idempotency-Key")
}
if _, ok := operationByID(t, spec, "UpdateOrganization").Responses["412"]; !ok {
t.Error("UpdateOrganization does not declare 412")
}
// Nothing in the organization paths sets a verification level or a role.
for path, item := range spec.Paths {
if !strings.HasPrefix(path, "/api/v1/organizations") && path != myOrganizationsPath {
continue
}
for _, operation := range []*ogen.Operation{item.Get, item.Post, item.Put, item.Patch, item.Delete} {
if operation == nil {
continue
}
id := strings.ToLower(operation.OperationID)
if strings.Contains(id, "verification") || strings.Contains(id, "verify") || strings.Contains(id, "role") || strings.Contains(id, "promote") {
t.Errorf("%s %s sets a level or a role", path, operation.OperationID)
}
}
}
}