Skip to content

Batch anonymous authorization checks per object - #6257

Merged
tdonohue merged 7 commits into
DSpace:mainfrom
bram-atmire:item-page-request-reduction
Nov 13, 2026
Merged

tdonohue merged 7 commits into
DSpace:mainfrom
bram-atmire:item-page-request-reduction

Conversation

@bram-atmire

@bram-atmire bram-atmire commented Sep 20, 2026 •

Copy link
Copy Markdown
Member

References

Fixes #6256. Related to the request-batching discussion in #3161.
Companion backend guard: DSpace/DSpace#13134. This request reduction uses the existing REST API and does not require that companion change or a REST contract change.

Description

Batch anonymous authorization checks per object using /authz/authorizations/search/object without a feature filter. The backend evaluates permissions once per object request; Angular selects each requested feature from the returned grants. This replaces the hardcoded list of features assumed to be denied anonymously.

On the measured anonymous item page, 14 authorization requests become 2 (site and item), and total API requests fall from 39 to 27. All 14 individual decisions match the batched results, including public COAR discovery. There is no metadata catalogue request.

Authenticated visitors and explicit-EPerson queries retain individual checks. Anonymous batching uses the existing request cache for pending-request deduplication, expiry, invalidation and SSR transfer; it adds no separate permission cache. It follows all pagination links before deciding that a feature is absent. If any page fails, it falls back to the individual feature request, preserving behavior on installations with a broken custom feature.

Authentication readiness follows the same blocking flag used by application initialization. The previous loaded check never completed for successful anonymous initialization.

Measurements

Production builds, one public item, same local backend/data, HTML page caches disabled. Four process runs in baseline/revised/revised/baseline order; each includes one initial render and ten warm renders. The baseline is the pre-PR authorization service at 2f1bf85ce2ea.

Metric Before After
Authorization API requests 14 2
Total API requests 39 27
Feature catalogue requests 0 0
COAR inbox HTML link and HTTP Link header Present Present

Counts were identical across all 22 renders per variant. Median warm full-response time was 270→262 ms; timings varied by run order, so this is not a demonstrated latency or throughput improvement. The measured benefit is 12 fewer HTTP requests (86% fewer authorization requests; 31% fewer total API requests). The original PR performance claims are superseded.

Browser verification: authorization GETs were 2 during hydration, 1 when navigating to a new item, and 0 on returning to the first item. CORS adds matching OPTIONS preflights. Item content and COAR inbox links were preserved with no JavaScript exceptions.

Instructions for Reviewers

  1. Enable ldn.enabled and visit a public item anonymously with server page caching disabled. Expect two unfiltered authorization searches (site and item), with embed=feature and size=100, instead of one search per feature.
  2. Confirm COAR inbox links in the HTML and HTTP Link header, and configuration/policy-dependent features such as QA and anonymous edit grants.
  3. Navigate to another item: expect one authorization lookup for the new item; the site result should be reused. Return to the first item and check cache reuse.
  4. Log in and verify ordinary feature checks and edit controls. Explicit-EPerson checks must retain their original path.
  5. Return a batch error, or fail a later page: confirm fallback to individual feature checks. Verify pagination with a granted feature appearing after the first page.

Validation: 137 selected Angular tests passed (including a rerun of the affected tests); production browser and SSR builds passed. Full source lint passed with generated decorator registries excluded, and no source circular dependencies were found with those generated files excluded. The standard checks still encounter pre-existing generated-registry lint errors/cycles; full CI and Docker-based end-to-end tests remain pending. No new dependencies, UI text or configuration options.

Checklist

This checklist provides a reminder of what we are going to look for when reviewing your PR. You do not need to complete this checklist prior creating your PR (draft PRs are always welcome).
However, reviewers may request that you complete any actions in this list if you have not done so. If you are unsure about an item in the checklist, don't hesitate to ask. We're here to help!

  • My PR is created against the main branch of code (unless it is a backport or is fixing an issue specific to an older branch).
  • My PR is small in size (e.g. less than 1,000 lines of code, not including comments & specs/tests), or I have provided reasons as to why that's not possible.
  • My PR follows all coding best practices based on the Code Conventions Guide
  • My PR passes ESLint validation using npm run lint
  • My PR doesn't introduce circular dependencies (verified via npm run check-circ-deps)
  • My PR includes TypeDoc comments for all new (or modified) public methods and classes. It also includes TypeDoc for large or complex private methods.
  • My PR passes all specs/tests and includes new/updated specs or tests based on the Code Testing Guide.
  • My PR aligns with Accessibility guidelines if it makes changes to the user interface.
  • My PR uses i18n (internationalization) keys instead of hardcoded English text, to allow for translations.
  • My PR includes details on how to test it. I've provided clear instructions to reviewers on how to successfully test this fix or feature.
  • If my PR includes new libraries/dependencies (in package.json), I've made sure their licenses align with the DSpace BSD License based on the Licensing of Contributions documentation.
  • If my PR includes new features or configurations, I've provided basic technical documentation in the PR itself.
  • If my PR fixes an issue ticket, I've linked them together.

Implementation and validation assisted by OpenAI Codex.

An anonymous item render fires ~15 per-feature authorization checks, about ten
of which ask about admin/edit/login-only capabilities an unauthenticated
visitor can never hold. AuthorizationDataService.isAuthorized now answers
false locally, without a REST call, for those features when no one is logged
in, and waits for isAuthenticationLoaded() before deciding so authenticated
users are never transiently treated as anonymous.

Measured on a local DSpace 11 stack with OpenTelemetry tracing: an anonymous
item render drops from 42 to 31 backend calls (15 to 5 authorization checks)
and single-core SSR render throughput rises ~45%.

Refs DSpace#6256, DSpace#3161

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
@lgeggleston lgeggleston added bug improvement authorization related to authorization, permissions or groups performance / caching Related to performance, caching or embedded objects labels Sep 23, 2026
@lgeggleston lgeggleston moved this to 🙋 Needs Reviewers Assigned in DSpace 11.0 Release Sep 23, 2026
@lgeggleston

Copy link
Copy Markdown
Contributor

Hi @bram-atmire, thanks for the PR! Would you be able to add the complete PR checklist to the description? Also you may have already seen, but this is currently running into a few errors in the CI (looks like just linting).

@MMilosz
MMilosz self-requested a review September 25, 2026 06:38
@MMilosz

MMilosz commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

This is a big step towards a good idea. Cutting waste on anonymous traffic-the largest load contributor-feels like exactly the right place to optimize

After checking the code, I have a tiiiny comment regarding the open design question you asked:

The authenticated-only feature set is a static list in AuthorizationDataService. That holds for every deployment I know of, but the edit/write features check a policy the backend genuinely evaluates, so a static list steps slightly outside the policy-driven model.

Personally, I lean toward the backend-first approach rather than frontend changes. Genuine question, did you already consider defining the whitelist directly in the backend instead of the frontend?

This is my "open design question for open design question", but how would you feel about this alternative:

  1. In the backend, let each Feature declare its own requirement (e.g., an enum flag like, for example EPersonRequirement.REQUIRED)
  2. Then, introduce a guard in AuthorizationFeatureServiceImpl#isAuthorized : if (feature.getEPersonRequirement() == EPersonRequirement.REQUIRED && context.getCurrentUser() == null) { return false; }
  3. Ultimately, expose a whitelist of features via the API (refactor an existing endpoint like /api/authz/features, currently, it's admin-only)
  4. Then, have Angular fetch it once (and perhaps cache it for a while) to use it on the client side

Does that make sense?

My reasoning for the backend-first approach is that:

  • A static UI list tightly couples the frontend to backend authorization internals
  • To extend the list, someone has to read through the backend *Feature.java implementations to find which ones check getCurrentUser() != null (which I suspect is how you prepared the Feature list in the PR)
  • What's important is that Features vary in what they depend on:
    • authentication "what EPerson are you?"
    • authorization "do you have a policy? are you in a group?"
    • config "is it enabled?" (QAAuthorizationFeature only check if qaevents.enabled is true)
    • or, a mix of all

Happy to see this moving. Overall, great work (on all your PRs lately)!

@bram-atmire bram-atmire changed the title Skip authenticated-only authorization checks for anonymous visitors Batch anonymous authorization checks per object Sep 26, 2026
@bram-atmire

bram-atmire commented Sep 26, 2026 •

Copy link
Copy Markdown
Member Author

@MMilosz, thank you for the review & feedback!! I agree that the backend should own the permission decisions. I removed the hardcoded frontend list. Your distinction between authentication, policy and configuration was important: QA/COAR can be enabled anonymously, and some edit/manage features can be granted through Anonymous resource policies.

The companion backend PR, DSpace/DSpace#13134, adds a default-false requiresAuthentication() declaration and the shared guard you suggested. Only features already guaranteed to reject a null context user opt in; policy-dependent and configuration features retain their existing behavior.

For the HTTP request reduction, I switched Angular to the existing all-features object search. A conservative authentication-only list plus a catalogue fetch gave no net request saving on the tested item page. The revised batching shares one lookup per object and selects each feature from the grants returned by the backend. It follows pagination, uses the existing request cache/invalidation, and falls back to individual checks if a batch fails. Logged-in and explicit-EPerson checks retain their original path. No new public metadata endpoint/property is needed.

The updated production SSR measurements are 14 → 2 authorization requests and 39 → 27 total API calls, consistent across 22 renders per variant. All 14 decisions matched the individual requests, and both HTML and HTTP COAR inbox links were preserved. Browser navigation required one authorization GET for a new item and none when returning to the cached item. I replaced the earlier performance claims; the timing sample does not establish a reliable throughput gain.

@lgeggleston, the complete PR checklist and updated validation/reviewer instructions are now in the description. The original import-order lint issue is fixed. Local selected tests and production builds passed; the standard lint/circular checks still report generated-registry issues as documented in the description, and CI for this revision is pending.

@tinsch

tinsch commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

I did a performance test on this PR and it showed a response time increase of about 100 - 150ms per item page load. This was tested on an item with 50 bitstreams per page, 100 iterations per test, multiple test runs.

The performance degradation was unexpected. I'd say it is not a blocker per se for merging this, but nevertheless worth looking into where the performance degradation stems from.

I did not use the Backend PR in the testing. Is this now necessary? The instructions for reviewers were not so clear on that.

@bram-atmire

Copy link
Copy Markdown
Member Author

I did a performance test on this PR and it showed a response time increase of about 100 - 150ms per item page load. This was tested on an item with 50 bitstreams per page, 100 iterations per test, multiple test runs.

Thank you for the testing!! Any clue where the extra 100-150ms per page load is coming from. E.g which requests are slower?

The performance degradation was unexpected. I'd say it is not a blocker per se for merging this, but nevertheless worth looking into where the performance degradation stems from.

Personally I would consider performance degradation a blocker. No point in merging something intended to make performance better if in fact, it makes it worse.

I did not use the Backend PR in the testing. Is this now necessary? The instructions for reviewers were not so clear on that.

Not necessary, but with the back end companion PR in place it should be faster.

@tinsch

tinsch commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

@bram-atmire thanks for appreciating the tests!

I ran some more to verify my findings from yesterday. Unfortunately I was able to reproduce them in a slightly different test setting again. Yesterday I only tested the SSR performance, today I tested the whole CSR and used largest contentful paint (LCP) as the measurement value. The results are as follows:

branch LCP avg over 100 iterations
main 2220.00ms
frontend-PR 2511.40ms
frontend-PR + backend PR 2511.68ms

From looking at the code, I don't believe single REST calls are suddenly slower. It is more likely that the new logic that was introduced takes longer to compute. Yesterday I debugged it a bit and tried to fix it with the help of an LLM (since I am not fluent in Typescript and Angular) and I would say one problem could be testing if oneAuthorizationMatchesFeature(featureId) only at the end of the function. It does not finish early if there is a match. Nevertheless I was not able to fix it after debugging, or more precisely my attempted fix did not change the performance outcome.

It is also possible that my test setup does not profit from the code optimizations, since each test run is isolated from each other. I understood the reviewer instructions above that only the second request to any item benefits from the performance optimization. Btw, what does "enable ldn.enabled" mean?

I am still not entirely sure what the code in this PR here does. I thought we might be able to perform just one authorization check per item page, find out that the user is not logged in (= anonymous user), and then not trigger any more authorization checks on features that require a log in. If we trigger less requests in that case, my tests should be able to verify the performance optimization, like with the changes and tests I did earlier this year. But I guess it is not so easy unfortunately.

@bram-atmire

Copy link
Copy Markdown
Member Author

@tinsch I've been able to replicate similar findings in load tests. I'm looking for the root cause & remediation now.

@bram-atmire

bram-atmire commented Oct 2, 2026 •

Copy link
Copy Markdown
Member Author

@tinsch I think I got it & that it's resolved now. Would highly appreciate if you could test the latest code on the branch to see if you can confirm the same.

Benchmark follow-up: avoid repeated anonymous feature scans

Code inspection confirmed that the batch endpoint request was reused by the request cache, but each anonymous isAuthorized check independently traversed the returned authorization list and resolved every feature link. The Angular change in 3a45c31e9 now shares the per-object feature-ID result across checks and clears it with authorization cache invalidation.

A focused matched SSR run on public-50 compared the original PR build with the optimized PR build: 40 measured renders per variant (20 in each of two blocks), warmups excluded, alternating PR/optimized/optimized/PR. The original PR had a 1,338 ms median and 1,514 ms p95; the optimized build had a 930 ms median and 1,055 ms p95, about 31% lower for both. The focused Angular authorization service suite passes (38 tests).

This supports the repeated Angular-side processing hypothesis and shows a substantial improvement for this SSR fixture. It is a targeted SSR result; browser/CSR and concurrency runs have not yet been repeated for the optimized build. The earlier broader run showed public SSR, browser LCP, and CSR slower on the original PR than main despite fewer API calls, which motivated this follow-up.

@tinsch

tinsch commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Thanks @bram-atmire for looking into it! I can confirm that the changes fixed the performance outcome. My CSR-tests show a drop from 2147.44ms on main to 1825.64ms with the PR applied. Well done 👏

Just one small thing: Could you fix the linting errors?

The spec relied on the real AuthorizationDataService being created for
FileDownloadLinkComponent. Now that the service depends on AuthService,
that construction fails with a missing AuthRequestService provider,
which the test runner also reports as a circular dependency. Provide
the existing stub, as other component specs do.

Assisted-by: Claude Code [claude-opus-5-5]
@bram-atmire

Copy link
Copy Markdown
Member Author

Thanks for testing and measuring this, @tinsch! The lint errors were fixed on 10-05, which then exposed a unit test failure: FileSectionComponent's spec was building the real AuthorizationDataService, which now depends on AuthService. I've stubbed it as other component specs do, and merged the latest main, which includes the fix for the flaky AuthService spec (#6326). The full unit test suite passes locally (5979 tests).

This comment was drafted with the help of Claude Code (AI); I reviewed it before posting.

@tdonohue
tdonohue requested a review from tinsch October 9, 2026 13:29
@tinsch

tinsch commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

@tdonohue I cannot do a code review on this one, all I could do is run the performance tests again (which I think is not necessary, given the recent changes where only test adjustments and linting fixes). I am just not fluent enough in Typescript and Angular to do a full code review.

@tdonohue

Copy link
Copy Markdown
Member

@tinsch : My apologies, I wasn't attempting to request a code review from you. I just saw that you'd given feedback and that feedback was addressed. So, I was pinging you to see if you wanted to re-test to potentially give it a +1. Unfortunately, GitHub doesn't have a way to separate out testers from code reviewers (they are all together in the "Reviewers" list).

So, when I clicked to have you re-review, I was just asking for a re-test or simply verifying your feedback has been addressed. :) In general, if I request a re-review, you are welcome to consider that just a request to either re-test or re-review code (the choice is yours, based on what you have time for or feel comfortable with).

@FrancescoMolinaro
FrancescoMolinaro self-requested a review October 29, 2026 15:57

@artlowel artlowel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @bram-atmire, I think it's a good idea!

I just have a few inline comments

Remove the per-object feature ID memo. The request cache already
deduplicates the identical unfiltered searches, and the memo's own
expiry did not follow request-cache invalidation. Move pagination into
findAllAuthorizationsForObject and handle every failure with a single
fallback to the individual feature check.

Resolving the feature links no longer waits for a successful response:
a failed feature link now errors, triggering that fallback instead of
leaving the check pending.

Assisted-by: Claude Code [claude-opus-5-5]

@artlowel artlowel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @bram-atmire!

@github-project-automation github-project-automation Bot moved this from 👀 Under Review to 👍 Reviewer Approved in DSpace 11.0 Release Nov 13, 2026
@bram-atmire

Copy link
Copy Markdown
Member Author

@tdonohue would you be able/willing to merge based on the current state (Atmire contributed, Atmire reviewed) or do you prefer to seek another reviewer?

@FrancescoMolinaro

Copy link
Copy Markdown
Contributor

Hi @bram-atmire , many thanks for your work on this, I also gave a look and tested your implementation and it looks great! I am also a +1 on this one

@tdonohue

Copy link
Copy Markdown
Member

Thanks @bram-atmire ! Because this is a performance-related fix, I'm going to flag this for auto-backport to 10.x and 9.x. I'm not entirely sure whether that auto-backport will succeed, but it makes sense to try to backport anything performance-related.

(Note: I've skipped backport to 8.x as I'm pretty certain the backport will fail there. The code on that branch is less similar to main. That said, I'd be supportive of backporting this further if anyone wants to do so.)

@tdonohue tdonohue added port to dspace-9_x This PR needs to be ported to `dspace-9_x` branch for next bug-fix release port to dspace-10_x This PR needs to be ported to `dspace-10_x` branch for next bug-fix release labels Nov 13, 2026
@tdonohue tdonohue added this to the 11.0 milestone Nov 13, 2026
@tdonohue
tdonohue merged commit db37a90 into DSpace:main Nov 13, 2026
16 checks passed
@github-project-automation github-project-automation Bot moved this from 👍 Reviewer Approved to ✅ Done in DSpace 11.0 Release Nov 13, 2026
@dspace-bot

Copy link
Copy Markdown
Contributor

Backport failed for dspace-9_x, because it was unable to cherry-pick the commit(s).

Please cherry-pick the changes locally and resolve any conflicts.

git fetch origin dspace-9_x
git worktree add -d .worktree/backport-6257-to-dspace-9_x origin/dspace-9_x
cd .worktree/backport-6257-to-dspace-9_x
git switch --create backport-6257-to-dspace-9_x
git cherry-pick -x ec77307c389773010832fb9e71425277eace9057 0a36bb02e847d8510d7af30f9a3c8363679ec1af 3a45c31e9f1d7429224b06b8547005d6b82fc6a4 0766e67b0d2ef272633c75b01e9c5994e4cdb30b 833726f05e564a8d5b5d08a8bb4ce6dfe1b6d7dd 6f522621291da128ed407fb078b1651df6314f1d

@dspace-bot

Copy link
Copy Markdown
Contributor

Backport failed for dspace-10_x, because it was unable to cherry-pick the commit(s).

Please cherry-pick the changes locally and resolve any conflicts.

git fetch origin dspace-10_x
git worktree add -d .worktree/backport-6257-to-dspace-10_x origin/dspace-10_x
cd .worktree/backport-6257-to-dspace-10_x
git switch --create backport-6257-to-dspace-10_x
git cherry-pick -x ec77307c389773010832fb9e71425277eace9057 0a36bb02e847d8510d7af30f9a3c8363679ec1af 3a45c31e9f1d7429224b06b8547005d6b82fc6a4 0766e67b0d2ef272633c75b01e9c5994e4cdb30b 833726f05e564a8d5b5d08a8bb4ce6dfe1b6d7dd 6f522621291da128ed407fb078b1651df6314f1d

@tdonohue

Copy link
Copy Markdown
Member

@bram-atmire : And, unfortunately none of the backports worked. So any backports would need to be done manually.

@tinsch

tinsch commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Unfortunately it seems these last changes were merged a bit prematurely. I ran the performance tests again and the results come back way worse than before:

branch page load (lcp) over 100 iterations
PR branch at commit 3ac0ffd (before) 1965.92ms
PR branch at commit 6f52262 (last commit, merged) 2490.02ms
main, before merge 2147.44ms

The whole point of this PR was to enhance the performance, therefore this degradation is a problem. I would encourage developers to run performance tests, or maybe we could include some kind of these tests in the pipeline. I personally use k6 by Grafana Labs to measure the performance: https://grafana.com/docs/k6/latest/

@tinsch

tinsch commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

If you want to run the tests yourself, this is my setup:

  • set up an item with 50 bitstreams
  • set the frontend config to
# Caching settings
cache:
  msToLive:
    default: 900000 # 15 minutes
  control: max-age=604800 # revalidate browser
  autoSync:
    defaultTime: 0
    maxBufferSize: 100
    timePerMethod:
      PATCH: 3 # time in seconds
  serverSide:
    debug: false
    botCache:
      max: 0
      timeToLive: 86400000 # 1 day
      allowStale: true
    anonymousCache:
      max: 0
      timeToLive: 10000 # 10 seconds
      allowStale: true

# Item Config
item:
  edit:
    undoTimeout: 10000 # 10 seconds
  showAccessStatuses: false
  bitstream:
    pageSize: 50
    showAccessStatuses: true

layout:
  showDownloadLinkAsAttachment: false
  • add your item's uuid and item's title and run the following k6 script:
import { browser } from 'k6/browser';
import { sleep, check, fail } from 'k6';

export const options = {
  summaryTimeUnit: 'ms',
  scenarios: {
    ui: {
      executor: 'shared-iterations',
      vus: 1,
      iterations: 100,
      options: {
        browser: {
          type: 'chromium',
          timeout: '3m'
        },
      },
      maxDuration: '2h',
    },
  },
};

export default async function () {
  let checkData;
  const page = await browser.newPage();

  try {
    await page.goto('http://localhost:4000/items/<your-items-uuid>');
    await page.waitForLoadState('load');
    const title = await page.title();
    check(title, {
      'page title is correct': (t) => t.includes('<your items title>'),
    });
  } catch (error) {
    fail(`Browser iteration failed: ${error.message}`);
  } finally {
    await page.close();
  }
  sleep(1);
}

@bram-atmire

Copy link
Copy Markdown
Member Author

I broke it with that last commit cfr Art's review. Working on a fix.

@bram-atmire

Copy link
Copy Markdown
Member Author

Once #6544 is merged, i'll do the backports

@tinsch

tinsch commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Thanks @bram-atmire for responding so quickly! I am not sure about the way to go, maybe we could also revert the merge and work on the new PR isolated from this merged PR?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

authorization related to authorization, permissions or groups bug improvement performance / caching Related to performance, caching or embedded objects port to dspace-9_x This PR needs to be ported to `dspace-9_x` branch for next bug-fix release port to dspace-10_x This PR needs to be ported to `dspace-10_x` branch for next bug-fix release

Projects

Status: ✅ Done

Development

Successfully merging this pull request may close these issues.

Skip authenticated-only authorization checks for anonymous visitors

8 participants