Skip to content

fix: encode user IDs in labels without loss - #122

Merged
uniqueg merged 8 commits into
devfrom
fix/user-label-encoding
Nov 9, 2026
Merged

uniqueg merged 8 commits into
devfrom
fix/user-label-encoding

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Summary

TESK API stored the creator of a task in the label creator-user-id as the sub with @ replaced by _. That encoding loses information (a@b and a_b get the same value) and doesn't fit every sub (label values allow at most 63 characters from [A-Za-z0-9._-]), so such users couldn't create tasks.

  • New encoding. New tasks get the label creator-user-hash (the first 32 hex digits, 128 bits, of the SHA-256 of the sub in UTF-8) and the annotation creator-user-id (the sub itself), on the taskmaster's job, its ConfigMap and the executors' jobs (CreatorLabels). The old label isn't written any more.
  • Exact matching. Kubernetes selects a user's tasks by the hash label; TESK API then checks each job: a task is the user's only if the annotation is the user's sub and the label is its hash (User#isCreatorOf, applied to every listed job for users with a label selector; admins and noauth, which have none, are unchanged). Getting and cancelling a task check User#isCreator on the task log, whose USER_ID now holds the verified sub. Group managers and admins keep their rights.
  • USER_ID in logs[0].metadata shows the sub unchanged (e.g. [email protected]).
  • Tasks created before have only the old label. By default they belong to no user (managers and admins see them as before). The new setting tesk.api.authorisation.legacy-user-labels (TESK_API_AUTHORISATION_LEGACY_USER_LABELS, default false) matches them by the old encoding for a transition; it only applies to tasks without the hash label. With it, the label selector of members and claim users names no creator (tasks may have either label), and TESK API filters after listing; pages can be shorter. An internal, non-serialized flag on TesTaskLog (userIdFromLegacyLabel) tells the check which kind of USER_ID it has; clients can't set it.
  • Taskmaster (tesk-core) doesn't read these labels: it copies the executors' jobs with their labels and annotations, so it needs no change.
  • Group names are unchanged: they are stored as they are (no lossy replacement), and only names of the user's own groups end up in labels.
  • Docs: docs/access-control.md (new "Task creators" section, claim section updated), docs/configuration.md (the setting), docs/upgrading.md (what operators do about old tasks: transition setting, how to list and delete them, rollback note).

Closes #119

Verification

Locally, in a Temurin 8 container (as CI):

  • ./mvnw -B spotless:check checkstyle:check: passes.
  • ./mvnw -B clean verify: 7393 unit tests and 83 integration tests pass, coverage checks met. New tests: CreatorLabelsTest, UserCreatorTest, list filtering in KubernetesClientWrapperTest (exact creator, old labels with and without the setting, managers), converter tests for the annotation and the old label, AuthIT (similar IDs, a sub longer than 63 characters with |, old-label tasks), LegacyUserLabelsIT (the setting on), updated fixtures.
  • mkdocs build --strict: passes.
  • After the refactor (79072c3, CreatorLabels#hash with Guava's Hashing.sha256() instead of MessageDigest, so that it has no unreachable branch, which codecov/patch had flagged) and a test for listed jobs without labels (d576a5f, the last partial branch that codecov/patch reported): ./mvnw -B spotless:check checkstyle:check clean verify passes again (7394 unit, 83 integration tests, coverage checks met; the hash test vectors are unchanged), and the changed lines have no uncovered line or branch in the JaCoCo reports.
  • After the Sourcery review: 5d83a4d (an object counts as created before the hash label only if it has neither the hash label nor the annotation; new tests CreatorLabelsTest#isLegacy_falseWithTheAnnotation, UserCreatorTest#isCreatorOf_oldLabelNotWithTheAnnotation) and 84adae9 (docs and test names): ./mvnw -B spotless:check checkstyle:check clean verify passes (7396 unit, 83 integration tests, coverage checks met); mkdocs build --strict passes.
  • CI: on 84adae9 (run 42546590663): all jobs passed (Lint, Test, Docs, Smoke test, Scan image, CI passed; Push image and Publish image skipped as intended on PRs); codecov/patch, codecov/project, CodeQL, Trivy and the Sourcery review check passed.

Review: round 1 (adversarial, quality): no high findings; medium (unused method, undocumented manual model change) and low findings fixed (constant renamed to LABEL_LEGACY_USERID_KEY, docs on claim-user listing, deleting old tasks, rolling updates). Round 2: the quality reviewer found nothing; the adversarial review of round 2 isn't needed, as round 1 had no high or medium adversarial findings and the logic didn't change after it. The refactor 79072c3 was reviewed by both reviewers: no findings (same output for every input, Hashing.sha256() is stable API in Guava 33.8.0-jre). The test d576a5f adds only a test. 5d83a4d (from the Sourcery review) was reviewed by both reviewers: no high findings; the adversarial reviewer found nothing wrong in any caller, the quality reviewer's medium findings (docs didn't state the rule; the kubectl selector for old tasks can't see the annotation) and low ones (test names) were fixed in 84adae9, which changes only docs and tests, so no further round.

Declined review findings

  • Sourcery: keep writing the old label during rolling updates. Declined: it would keep the old encoding in use for new tasks; the rolling-update window is documented in docs/upgrading.md (use Recreate, or accept it), and old tasks are covered by the transition setting.
  • Quality reviewer (5d83a4d), low: no converter test for an object with only the annotation. Declined: the converter takes the same isLegacy branch, which CreatorLabelsTest covers, and creatorId is null there (covered too).

🤖 Generated with Claude Code

Summary by Sourcery

Replace lossy creator labels with exact, hash-based task ownership metadata and add a controlled compatibility path for pre-existing tasks.

New Features:

  • Record task creators using a collision-resistant hash label and exact subject annotation across task Kubernetes resources.
  • Expose the unchanged user subject in task log metadata and support exact creator-based task authorization.

Bug Fixes:

  • Prevent creator ID collisions and label-size or character restrictions from denying access or task creation.
  • Ensure task listings, retrieval, and cancellation distinguish users with similar or legacy-encoded identifiers.

Enhancements:

  • Add an opt-in legacy-label transition mode for matching tasks created before the new creator metadata was introduced.
  • Filter Kubernetes task listings by verified creator metadata while preserving manager and administrator access.

Documentation:

  • Document creator metadata, legacy-label behavior, configuration, upgrade steps, cleanup, and rollback considerations.

Tests:

  • Add unit and integration coverage for creator hashing, exact matching, legacy compatibility, task listing, and long or ambiguous subjects.

uniqueg and others added 3 commits November 8, 2026 20:11
Record the creator of a task in the label creator-user-hash (the first
128 bits of the SHA-256 of the sub, in hex) and the annotation
creator-user-id (the sub itself), instead of the label creator-user-id
with @ replaced by _. Any sub now fits, also one that is longer than 63
characters or has characters that labels don't allow, and IDs such as
a@b and a_b are told apart.

Kubernetes selects a user's tasks by the hash label; TESK API then
checks the annotation (and its hash) of each job, and of each task it
gets, so that only the exact ID counts. USER_ID in the task log shows
the sub unchanged.

Tasks created before have only the old label. They belong to no user
by default (group managers and admins see them as before); the setting
tesk.api.authorisation.legacy-user-labels matches them by the old label
for a transition. The selector then names no creator, and the
creator is checked after listing.

Refs #119

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Document the label creator-user-hash and the annotation creator-user-id
(access control), the setting TESK_API_AUTHORISATION_LEGACY_USER_LABELS
(access control, configuration), and what operators do about tasks
with only the old label when they upgrade.

Refs #119

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Rename the old label's constant to LABEL_LEGACY_USERID_KEY and point
out that the annotation shares its key. Remove
isMemberInNonManagedGroups, which the list filter no longer uses. Move
the internal flag of TesTaskLog to the end of the class, hide it from
the API description and name it in the notes on regenerating the
model. Split the tests of User#isCreator.

Docs: listing with the transition setting affects users authorised by
the claim too; deleting old tasks by label deletes running ones, too,
and their ConfigMaps can be deleted the same way; a rolling update
with several replicas briefly mixes both encodings.

Refs #119

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v1.2.0 milestone Nov 8, 2026
@uniqueg uniqueg added the type: bug Something isn't working label Nov 8, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Schema and migrations

Define the persisted creator-label and annotation keys, hash encoding, validation of creator metadata, and legacy-object detection that the rest of the authorization flow relies on.

  • src/main/java/uk/ac/ebi/tsc/tesk/k8s/constant/Constants.java L73-91
  • src/main/java/uk/ac/ebi/tsc/tesk/k8s/convert/CreatorLabels.java L1-78

Data structures

Add a non-serialized marker to task logs so authorization can distinguish a legacy label value from a verified user ID.

  • src/main/java/uk/ac/ebi/tsc/tesk/tes/model/TesTaskLog.java L4, L249-266

API

Change task retrieval authorization to use the creator-aware check while preserving group-manager and administrator access.

  • src/main/java/uk/ac/ebi/tsc/tesk/tes/service/TesService.java L40-43

Uses of the API

Filter Kubernetes task listings by group-manager rights or the verified creator, while adjusting selectors for legacy-label transition mode.

  • src/main/java/uk/ac/ebi/tsc/tesk/k8s/service/KubernetesClientWrapper.java L19, L273-283, L288-293

Implementation

Update the authenticated user model to retain the exact subject, recognize verified and optionally legacy creators, and build suitable Kubernetes label selectors.

  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/User.java L45-51, L82-118, L436-440 (+16 small edits)

Write the hash label and full-subject annotation to created Kubernetes objects, and reconstruct verified or legacy creator metadata in task logs.

  • src/main/java/uk/ac/ebi/tsc/tesk/k8s/convert/TesKubernetesConverter.java L373-390 (+5 small edits)

Configuration

Expose and default the opt-in legacy-label matching setting, then pass it from authorization properties into the authenticated user.

  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/AuthorisationProperties.java L41-48, L91-98
  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/ElixirPrincipalExtractor.java L155
  • src/main/resources/application.properties L51-53

Documentation

Explain creator identity, legacy-task access and the transition setting in access-control and configuration documentation.

  • docs/access-control.md L89-117, L175-176
  • docs/configuration.md L33

Document upgrade and rollback implications, cleanup of legacy tasks, and the manually maintained task-log model field.

  • docs/development.md L188-189
  • docs/upgrading.md L7-47

Tests

Verify creator hashing, exact and legacy authorization, Kubernetes listing filters, and conversion of creator metadata into and out of Kubernetes objects.

  • src/test/java/uk/ac/ebi/tsc/tesk/config/security/ClaimAuthorisationTest.java L155-156, L173-184
  • src/test/java/uk/ac/ebi/tsc/tesk/config/security/UserCreatorTest.java L1-156
  • src/test/java/uk/ac/ebi/tsc/tesk/k8s/convert/CreatorLabelsTest.java L1-100
  • src/test/java/uk/ac/ebi/tsc/tesk/k8s/convert/TesKubernetesConverterMinimalTest.java L133-138, L202, L319-355
  • src/test/java/uk/ac/ebi/tsc/tesk/k8s/convert/TesKubernetesConverterTest.java L224-229, L349-354
  • src/test/java/uk/ac/ebi/tsc/tesk/k8s/service/KubernetesClientWrapperTest.java L317-323, L513-526, L543-644 (+3 small edits)

Exercise end-to-end behavior for exact IDs, long subjects, legacy tasks, authorization modes, and listings.

  • src/integration-test/java/uk/ac/ebi/tsc/tesk/AuthIT.java L564-569, L729-826 (+7 small edits)
  • src/integration-test/java/uk/ac/ebi/tsc/tesk/ClaimAuthIT.java L220-229, L255-259 (+8 small edits)
  • src/integration-test/java/uk/ac/ebi/tsc/tesk/LegacyUserLabelsIT.java L1-124
  • src/integration-test/java/uk/ac/ebi/tsc/tesk/MockUtil.java L8-25, L59-118
  • src/integration-test/java/uk/ac/ebi/tsc/tesk/NoAuthIT.java L76

Other changes

Files not grouped.

  • src/integration-test/resources/__files/list/executors.json L6-66 (4 small edits)
  • src/integration-test/resources/__files/list/taskmasters.json L7-12, L30-35, L54-59 (+1 small edits)
  • src/integration-test/resources/__files/task-123/executor.json L6
  • src/integration-test/resources/__files/task-123/taskmaster.json L3-8
  • src/test/resources/fromTesToK8s/job.json L11
  • src/test/resources/fromTesToK8s/taskmaster_param.json L43-119 (4 small edits)
  • src/test/resources/fromTesToK8s_minimal/job.json L10
  • src/test/resources/fromTesToK8s_minimal/taskmaster_param.json L14, L20

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 65.62%. Comparing base (3880cbf) to head (1f82150).

Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #122      +/-   ##
==========================================
+ Coverage   65.00%   65.62%   +0.62%     
==========================================
  Files          66       67       +1     
  Lines        2626     2668      +42     
  Branches      272      280       +8     
==========================================
+ Hits         1707     1751      +44     
  Misses        769      769              
+ Partials      150      148       -2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

uniqueg and others added 2 commits November 9, 2026 01:49
Use Hashing.sha256 instead of MessageDigest, so that hash() has no
unreachable branch for a missing SHA-256 implementation. The values are
unchanged (the test vectors in CreatorLabelsTest still pass).

Refs #119

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cover the branch of KubernetesClientWrapper#groupOf for jobs without
labels: the filter leaves them out, also with only the creator
annotation and with the legacy-label setting on.

Refs #119

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg marked this pull request as ready for review November 9, 2026 01:09

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/main/java/uk/ac/ebi/tsc/tesk/k8s/convert/CreatorLabels.java" line_range="50" />
<code_context>
+
+    /** Whether the object was created before the hash label: it has none */
+    public static boolean isLegacy(V1ObjectMeta metadata) {
+        return get(metadata.getLabels(), LABEL_USERHASH_KEY) == null;
+    }
+
</code_context>
<issue_to_address>
**Hybrid metadata grants legacy access**

When the transition setting is enabled and a hashless object has both an annotation and a colliding legacy creator label, `User.isCreatorOf` treats any object without a hash label as legacy, and `legacyCreator` ignores its annotation. With the transition setting enabled, a hashless object carrying an annotation for one `sub` and a colliding old label for another is authorized to the wrong user.

Treat an object as legacy only when it has no creator annotation as well as no hash label, and add a mixed-metadata test.
</issue_to_address>

### Comment 2
<location path="src/main/java/uk/ac/ebi/tsc/tesk/k8s/convert/TesKubernetesConverter.java" line_range="80" />
<code_context>
         taskMasterJob.getMetadata().putAnnotationsItem(ANN_TESTASK_NAME_KEY, task.getName());
         // creating user and owning group
-        taskMasterJob.getMetadata().putLabelsItem(LABEL_USERID_KEY, user.getUsername());
+        CreatorLabels.put(taskMasterJob.getMetadata(), user.getUsername());
         if (task.getTags() != null && task.getTags().containsKey("GROUP_NAME")) {
             taskMasterJob
</code_context>
<issue_to_address>
**Creator tasks disappear or return 403s**

When a multi-replica deployment is rolling out and serves requests from both versions, `CreatorLabels.put` writes only the hash label and new replicas select by it, while old replicas look for the legacy label, so requests routed across versions cannot consistently list or authorize a creator's tasks and return missing tasks or 403s.

Preserve compatibility between the old and new creator labels during rolling updates so both versions can find and authorize the same tasks.

Also at `src/main/java/uk/ac/ebi/tsc/tesk/config/security/User.java:184`.
</issue_to_address>

Linked issues

#119 Encode user IDs in labels without loss · 6 of 7 met · 1 to check by hand

# Requirement Status Notes
1 Use a fixed-length hash label and full-ID annotation on the taskmaster job, ConfigMap, and executor jobs so arbitrary sub values fit and distinct IDs are distinguishable. ✅ Met CreatorLabels.put writes the hash label and full-ID annotation, and the converter applies it to all three object types.
2 Select tasks by hash, then verify the annotation against the user's exact ID; apply creator checks to listed, fetched, and cancelled tasks. ✅ Met Listing filters each selected job with isCreatorOf, which validates the annotation against its hash; get authorization uses isCreator on the task log. Cancellation calls getTask first, so it goes through the same post-authorization check.
3 Show the full sub unchanged in logs[0].metadata.USER_ID. ✅ Met The converter takes the verified ID from the annotation for new tasks and puts it in USER_ID.
4 Provide an off-by-default transition setting that matches tasks with only the old label by its old encoding, and document the upgrade steps. ✅ Met The setting is wired through authorization properties; legacy matching applies only when the hash label is absent. The access-control, configuration, and upgrading docs describe the setting and operator steps.
5 Keep admin and group-manager behaviour unchanged. ✅ Met Admins have no label selector and are not post-list filtered; managers retain tasks in managed groups through the group-manager check.
6 Document the labels, the transition setting, and what operators need to do about old tasks. ✅ Met The change adds the Task creators section and configuration and upgrade guidance, including listing and deleting old tasks.
7 Check whether the taskmaster (tesk-core) reads these labels. 👀 Check by hand (external system) The upgrade docs state that tesk-core copies executor jobs' labels and annotations without reading these labels; verify that behavior in the external tesk-core implementation.

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and if the creator hash and annotation checks or the post-listing filter are wrong, a user could be allowed to see or act on another user’s tasks; any task data accessed before a revert cannot be taken back. The opt-in legacy matching also deliberately restores a lossy identity comparison, so an ID collision could grant access while it is enabled.

Blocking findings: src/main/java/uk/ac/ebi/tsc/tesk/k8s/convert/CreatorLabels.java:50, src/main/java/uk/ac/ebi/tsc/tesk/k8s/convert/TesKubernetesConverter.java:80


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

uniqueg and others added 3 commits November 9, 2026 02:24
Treat an object as created before the hash label only if it has
neither the hash label nor the creator annotation. An object with the
annotation but without the hash label names no creator, also when the
legacy-label setting is on, instead of falling back to the old label.

Refs #119

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Say that a task with only the hash label or only the annotation names
no creator, also with the legacy-label setting, and that the kubectl
selector for old tasks also lists objects with the annotation. Name and
describe the new tests more precisely.

Refs #119

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 3f6ba2b into dev Nov 9, 2026
25 checks passed
@uniqueg
uniqueg deleted the fix/user-label-encoding branch November 9, 2026 01:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Encode user IDs in labels without loss

1 participant