linux-keyctl 1.1.0__tar.gz → 1.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/CHANGES.md +9 -0
  2. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/PKG-INFO +1 -1
  3. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/SPECIFICATIONS.md +60 -9
  4. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/docs/getting-started.rst +2 -1
  5. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/docs/integration.rst +12 -0
  6. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/docs/internals.rst +2 -0
  7. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/pyproject.toml +1 -1
  8. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/src/linux_keyctl/__init__.py +49 -1
  9. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/src/linux_keyctl/_syscall.py +1 -0
  10. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/src/linux_keyctl.egg-info/PKG-INFO +1 -1
  11. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/tests/test_linux_keyctl.py +127 -1
  12. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/.pycodestyle +0 -0
  13. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/LICENSE +0 -0
  14. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/MANIFEST.in +0 -0
  15. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/README.md +0 -0
  16. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/docs/_ext/module_reference.py +0 -0
  17. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/docs/_static/layout.css +0 -0
  18. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/docs/api.rst +0 -0
  19. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/docs/conf.py +0 -0
  20. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/docs/contributing.rst +0 -0
  21. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/docs/index.rst +0 -0
  22. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/docs/modules.rst +0 -0
  23. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/setup.cfg +0 -0
  24. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/src/linux_keyctl/py.typed +0 -0
  25. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/src/linux_keyctl.egg-info/SOURCES.txt +0 -0
  26. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/src/linux_keyctl.egg-info/dependency_links.txt +0 -0
  27. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/src/linux_keyctl.egg-info/requires.txt +0 -0
  28. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/src/linux_keyctl.egg-info/top_level.txt +0 -0
  29. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/tests/test_documentation.py +0 -0
  30. {linux_keyctl-1.1.0 → linux_keyctl-1.2.0}/tools/docs.py +0 -0
@@ -1,5 +1,14 @@
1
1
  # Changes
2
2
 
3
+ ## 1.2.0
4
+
5
+ - New `get_keyring_id(key_id, create=False)` (`KEYCTL_GET_KEYRING_ID`):
6
+ returns the real serial of a `KEY_SPEC_*` special keyring, or an
7
+ existing key's own serial. `create` accepts any `int`, `bool` included,
8
+ and is passed to the kernel as `0` or `1`. With `create=True` the kernel
9
+ may create the caller's thread or process keyring, or replace a session
10
+ keyring that is the user-session keyring with a new anonymous one.
11
+
3
12
  ## 1.1.0
4
13
 
5
14
  First release.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: linux-keyctl
3
- Version: 1.1.0
3
+ Version: 1.2.0
4
4
  Summary: Thin Python interface to the Linux kernel key management system calls
5
5
  Author: Juan Domingo Martín
6
6
  License-Expression: GPL-3.0-or-later
@@ -1,7 +1,7 @@
1
1
  # linux-keyctl — API Specification
2
2
 
3
3
  This document specifies the public interface of `linux-keyctl` (import name
4
- `linux_keyctl`), version **1.1.0**, precisely enough to implement it and to
4
+ `linux_keyctl`), version **1.2.0**, precisely enough to implement it and to
5
5
  write API-compatible test doubles. `linux-keyctl` is a pure-syscall
6
6
  implementation (§7.4).
7
7
 
@@ -165,6 +165,7 @@ KeyInfo
165
165
  add_key link unlink read_key update_key search clear describe_key
166
166
  key_info set_perm set_timeout revoke invalidate session_to_parent
167
167
  join_session_keyring request_key move_key new_keyring list_keyring
168
+ get_keyring_id
168
169
  ```
169
170
 
170
171
  Requirements:
@@ -176,7 +177,8 @@ Requirements:
176
177
  appear as non-underscore attributes; they are not part of the API.
177
178
  - `linux_keyctl.__version__` is a `str` in `MAJOR.MINOR.PATCH` form: the
178
179
  version of the `linux-keyctl` distribution (it MUST match the packaging
179
- metadata). It follows §8. The first release is `"1.1.0"`.
180
+ metadata). It follows §8. The first release is `"1.1.0"`; 1.2.0 added
181
+ `get_keyring_id` (§7.2).
180
182
 
181
183
  ---
182
184
 
@@ -213,9 +215,9 @@ constants are plain `int`; key types are `bytes`.
213
215
  | `KEY_REQKEY_DEFL_GROUP_KEYRING` | `6` |
214
216
  | `KEY_REQKEY_DEFL_REQUESTOR_KEYRING` | `7` |
215
217
 
216
- > Note: these are exported but **no function consumes them** in 1.1.0.
217
- > `set_reqkey_keyring()` is not part of 1.1.0; it MAY be added as an
218
- > extension (see §8).
218
+ > Note: these are exported but **no function consumes them** (as of
219
+ > 1.2.0). `set_reqkey_keyring()` is not part of the API yet; it MAY be
220
+ > added as an extension (see §8).
219
221
 
220
222
  ### 4.3 Move flags
221
223
 
@@ -299,6 +301,11 @@ class KeyInfo(typing.NamedTuple):
299
301
  `move_key(flags)` (C `unsigned int`, `0 … 2**32-1`) MUST raise
300
302
  `OverflowError` outside their range. A non-`int` integer argument MUST
301
303
  raise `TypeError`.
304
+ - `get_keyring_id(create)` is a flag (C `int`). Any `int`, `bool`
305
+ included, MUST be accepted and passed as `1` if nonzero, `0` otherwise,
306
+ never as the value itself: `2**32` would otherwise truncate to `0` and
307
+ turn "create" into "don't create". A non-`int` (`str`, `None`, `float`,
308
+ …) MUST raise `TypeError`.
302
309
 
303
310
  ### 6.2 Error model
304
311
 
@@ -504,6 +511,48 @@ functions raise per §6.2 on kernel failure.
504
511
  #### `session_to_parent() -> int`
505
512
  - C: `keyctl_session_to_parent()`. No arguments. Returns 0. See §6.3.
506
513
 
514
+ #### `get_keyring_id(key_id: int, create: bool = False) -> int`
515
+ - C: `keyctl_get_keyring_ID(key_id, create)`, with `create` passed as `0`
516
+ or `1` (§6.1). Added in 1.2.0.
517
+ - Returns the serial of the key `key_id` names. For a `KEY_SPEC_*` value
518
+ that is the real serial of the caller's special keyring. Callers need it
519
+ to compare a special keyring with serials from other calls (e.g.
520
+ `list_keyring`), to keep naming a keyring after the caller's keyrings
521
+ change, or to pass it to another process, where the `KEY_SPEC_*` value
522
+ would name that process's own keyring. An ordinary serial, of any key
523
+ type, is returned unchanged if the key exists.
524
+ - The caller needs SEARCH permission on the key (`EACCES` otherwise).
525
+ Without `KEY_POS_SEARCH` the key is not possessed and the `KEY_USR_*`
526
+ bits apply (§1.3).
527
+ - Side effects, which are the kernel's (`lookup_user_key()` in
528
+ `security/keys/process_keys.c`) and MUST be passed through, not guarded
529
+ against:
530
+ - `create` true creates a missing thread (`_tid`) or process (`_pid`)
531
+ keyring for the caller.
532
+ - `KEY_SPEC_SESSION_KEYRING` with `create` true makes the calling
533
+ process join a new anonymous session keyring (`_ses`) if its session
534
+ keyring is the user-session keyring, i.e. **replaces** the session
535
+ keyring, as `join_session_keyring()` would. A process with no session
536
+ keyring at all gets one installed on any lookup: a new anonymous one
537
+ with `create`, the user-session keyring without.
538
+ - The user and user-session keyrings are created on lookup whatever
539
+ `create` is.
540
+ - Observed on Linux 6.12.117 (x86_64), in a process that had joined a new
541
+ anonymous session keyring unless stated otherwise:
542
+
543
+ | `key_id` | `create` false | `create` true |
544
+ |---|---|---|
545
+ | `KEY_SPEC_THREAD_KEYRING`, `KEY_SPEC_PROCESS_KEYRING`, none yet | `ENOKEY` | new `_tid` / `_pid` keyring; later calls return it with either `create` |
546
+ | `KEY_SPEC_SESSION_KEYRING` | the session keyring (the serial `join_session_keyring` returned) | same |
547
+ | `KEY_SPEC_SESSION_KEYRING`, after joining the user-session keyring by name | the user-session keyring | a new `_ses` keyring, now the session keyring |
548
+ | `KEY_SPEC_USER_KEYRING`, `KEY_SPEC_USER_SESSION_KEYRING` | `_uid.<uid>`, `_uid_ses.<uid>` | same |
549
+ | `KEY_SPEC_GROUP_KEYRING`, `0`, an unknown negative value (`-9`, `-100`) | `EINVAL` | `EINVAL` |
550
+ | `KEY_SPEC_REQKEY_AUTH_KEY`, `KEY_SPEC_REQUESTOR_KEYRING`, outside a request-key upcall | `ENOKEY` | `ENOKEY` |
551
+ | Existing key or keyring with SEARCH permission | its serial | its serial |
552
+ | Serial that does not exist | `ENOKEY` | `ENOKEY` |
553
+ | Key without SEARCH permission, or no longer possessed | `EACCES` | `EACCES` |
554
+ | Revoked key / expired key | `EKEYREVOKED` / `EKEYEXPIRED` | same |
555
+
507
556
  ### 7.3 Summary table
508
557
 
509
558
  | Python | C call (argument order) | Returns |
@@ -527,6 +576,7 @@ functions raise per §6.2 on kernel failure.
527
576
  | `move_key(key_id, from_keyring, to_keyring, flags=0)` | `keyctl_move(key_id, from_keyring, to_keyring, flags)` | 0 |
528
577
  | `new_keyring(descr, parent)` | `add_key(b'keyring', descr, b'', 0, parent)` | serial |
529
578
  | `list_keyring(keyring)` | `keyctl_describe` + `keyctl_read` | generator of `int` |
579
+ | `get_keyring_id(key_id, create=False)` | `keyctl_get_keyring_ID(key_id, 1 if create else 0)` | serial |
530
580
 
531
581
  ### 7.4 Syscall backend
532
582
 
@@ -537,7 +587,7 @@ each one as the system call below.
537
587
  |---|---|
538
588
  | `add_key`, `new_keyring` | `add_key(type, description, payload, plen, keyring)` |
539
589
  | `request_key` | `request_key(type, description, callout_info, dest_keyring)` |
540
- | everything else | `keyctl(op, arg2, arg3, arg4, arg5)` with `KEYCTL_*` op: `READ`=11, `UPDATE`=2, `DESCRIBE`=6, `SEARCH`=10, `CLEAR`=7, `LINK`=8, `UNLINK`=9, `SETPERM`=5, `SET_TIMEOUT`=15, `REVOKE`=3, `INVALIDATE`=21, `JOIN_SESSION_KEYRING`=1, `SESSION_TO_PARENT`=18, `MOVE`=30 |
590
+ | everything else | `keyctl(op, arg2, arg3, arg4, arg5)` with `KEYCTL_*` op: `READ`=11, `UPDATE`=2, `DESCRIBE`=6, `SEARCH`=10, `CLEAR`=7, `LINK`=8, `UNLINK`=9, `SETPERM`=5, `SET_TIMEOUT`=15, `REVOKE`=3, `INVALIDATE`=21, `JOIN_SESSION_KEYRING`=1, `SESSION_TO_PARENT`=18, `MOVE`=30, `GET_KEYRING_ID`=0 |
541
591
 
542
592
  libkeyutils's `keyctl_*` wrappers pass their arguments to `keyctl(2)`
543
593
  unchanged and in the same order, so the syscall argument order is the C
@@ -588,8 +638,6 @@ the arguments):
588
638
  useful candidates:
589
639
  - `set_reqkey_keyring(reqkey_defl)` (`KEYCTL_SET_REQKEY_KEYRING` = 14).
590
640
  Without it, the exported `KEY_REQKEY_DEFL_*` constants have no use.
591
- - `get_keyring_id(key_id, create=False)` (`KEYCTL_GET_KEYRING_ID` = 0),
592
- which turns `KEY_SPEC_*` values into real serials.
593
641
  - `chown(key_id, uid, gid)` (`KEYCTL_CHOWN` = 4) and `get_security`
594
642
  (`KEYCTL_GET_SECURITY` = 17).
595
643
  - `capabilities()` (`KEYCTL_CAPABILITIES` = 31), which lets callers detect
@@ -616,7 +664,7 @@ the arguments):
616
664
  ## 9. Conformance checklist
617
665
 
618
666
  - [ ] Distribution `linux-keyctl`, import name `linux_keyctl`; no top-level
619
- `keyctl` module installed; GPL-3.0-or-later license; version 1.1.0;
667
+ `keyctl` module installed; GPL-3.0-or-later license; version 1.2.0;
620
668
  `requires-python >= 3.11`; no compiled extension; no runtime
621
669
  dependencies beyond the standard library (§2).
622
670
  - [ ] Direct syscalls only; `libkeyutils` is never loaded. Syscall numbers
@@ -643,6 +691,9 @@ the arguments):
643
691
  - [ ] `list_keyring` is lazy, raises `NotADirectoryError` on non-keyrings,
644
692
  and yields native-endian `int` serials.
645
693
  - [ ] `new_keyring(d, p) == add_key(d, b'', p, KEY_TYPE_KEYRING)` semantically.
694
+ - [ ] `get_keyring_id` passes `create` as `0`/`1`, rejects a non-`int`
695
+ `create` with `TypeError`, and passes the kernel's side effects and
696
+ errors through (§7.2).
646
697
  - [ ] No logging/printing; no payload or description in any exception;
647
698
  no payload caching (§6.5).
648
699
  - [ ] `linux-keyctl`'s own test suite runs on a **real** kernel keyring (the
@@ -36,7 +36,8 @@ Store a secret in the session keyring, read it back, and revoke it::
36
36
 
37
37
  Descriptions, key types and payloads are ``bytes``; passing ``str`` raises
38
38
  ``TypeError``. Keys are identified by ``int`` serial numbers, and the
39
- ``KEY_SPEC_*`` constants name the calling process's special keyrings.
39
+ ``KEY_SPEC_*`` constants name the calling process's special keyrings;
40
+ :func:`~linux_keyctl.get_keyring_id` returns their real serial numbers.
40
41
 
41
42
  Errors
42
43
  ------
@@ -93,6 +93,12 @@ Secrets and side effects
93
93
  session keyring; :func:`~linux_keyctl.session_to_parent` changes the
94
94
  *parent's*. Do not call either from a library on behalf of a caller that
95
95
  did not ask for it.
96
+ * :func:`~linux_keyctl.get_keyring_id` with ``create=True`` can change the
97
+ caller's keyrings too: it creates a missing thread or process keyring,
98
+ and for ``KEY_SPEC_SESSION_KEYRING`` it *replaces* a session keyring
99
+ that is the user-session keyring with a new anonymous one. Without
100
+ ``create`` it only looks up; that is enough to get a serial for a
101
+ keyring that already exists.
96
102
 
97
103
  Kernel behaviour to plan for
98
104
  ----------------------------
@@ -108,6 +114,12 @@ Kernel behaviour to plan for
108
114
  :func:`~linux_keyctl.invalidate` frees a key at once.
109
115
  * **Sharing with services.** A service sees the caller's keys only if it
110
116
  shares the session or user keyring and has the matching permissions.
117
+ * **Special IDs are relative.** ``KEY_SPEC_SESSION_KEYRING`` and the other
118
+ ``KEY_SPEC_*`` values mean "the caller's keyring of that kind", resolved
119
+ on every call. Use :func:`~linux_keyctl.get_keyring_id` (added in 1.2.0)
120
+ for the real serial: to compare it with serials from
121
+ :func:`~linux_keyctl.list_keyring` or :func:`~linux_keyctl.search`, or
122
+ to hand it to another process.
111
123
 
112
124
  Testing a client
113
125
  ----------------
@@ -48,3 +48,5 @@ kernel cannot reproduce on demand, such as data growing between two reads
48
48
  or an unsupported architecture, are tested with replaced backends or in a
49
49
  subprocess. ``session_to_parent`` is only tested with a replaced backend,
50
50
  because a real call would change the test runner's session keyring.
51
+ ``get_keyring_id`` creates its thread keyring in a separate thread, and
52
+ replaces a session keyring only in a subprocess, for the same reason.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "linux-keyctl"
7
- version = "1.1.0"
7
+ version = "1.2.0"
8
8
  description = "Thin Python interface to the Linux kernel key management system calls"
9
9
  readme = "README.md"
10
10
  license = "GPL-3.0-or-later"
@@ -33,7 +33,7 @@ import typing as _typing
33
33
 
34
34
  from . import _syscall as _sys
35
35
 
36
- __version__ = "1.1.0"
36
+ __version__ = "1.2.0"
37
37
 
38
38
  # Special keyring IDs.
39
39
  KEY_SPEC_THREAD_KEYRING = -1
@@ -587,6 +587,53 @@ def session_to_parent() -> int:
587
587
  return _sys.keyctl(_sys.KEYCTL_SESSION_TO_PARENT)
588
588
 
589
589
 
590
+ def get_keyring_id(key_id: int, create: bool = False) -> int:
591
+ """Return the serial number of a special keyring or a key.
592
+
593
+ A ``KEY_SPEC_*`` value names a keyring relative to the caller:
594
+ ``KEY_SPEC_SESSION_KEYRING`` is whatever session keyring the caller
595
+ has now. This returns that keyring's serial, which stays valid
596
+ when the caller's keyrings change, can be compared with serials
597
+ from other calls and means the same in another process. An
598
+ ordinary serial is returned unchanged if the key exists.
599
+
600
+ With ``create`` true, a missing thread or process keyring is
601
+ created. For ``KEY_SPEC_SESSION_KEYRING``, ``create`` true makes the
602
+ calling process join a new anonymous session keyring if its session
603
+ keyring is the user-session keyring (the kernel's fallback when a
604
+ process has no session keyring of its own), replacing it as
605
+ :func:`join_session_keyring` would. The user and user-session
606
+ keyrings are always created if needed.
607
+
608
+ .. versionadded:: 1.2.0
609
+
610
+ Args:
611
+ key_id: A ``KEY_SPEC_*`` constant or a key ID.
612
+ create: Create the keyring if it does not exist. Any ``int``
613
+ is accepted; nonzero means true.
614
+
615
+ Returns:
616
+ The serial number.
617
+
618
+ Raises:
619
+ TypeError: ``create`` is not a ``bool`` or ``int``.
620
+ OSError: ``ENOKEY`` if the key does not exist, or the thread or
621
+ process keyring does not exist and ``create`` is false
622
+ (also for ``KEY_SPEC_REQKEY_AUTH_KEY`` and
623
+ ``KEY_SPEC_REQUESTOR_KEYRING`` outside a request-key
624
+ upcall); ``EINVAL`` for ``0``, ``KEY_SPEC_GROUP_KEYRING``
625
+ or an unknown negative ID; ``EACCES`` without SEARCH
626
+ permission; ``EKEYREVOKED`` or ``EKEYEXPIRED``.
627
+ """
628
+ if not isinstance(create, int):
629
+ raise TypeError("create: expected bool or int")
630
+ return _sys.keyctl(
631
+ _sys.KEYCTL_GET_KEYRING_ID,
632
+ _int("key_id", key_id),
633
+ 1 if create else 0,
634
+ )
635
+
636
+
590
637
  __all__ = [
591
638
  "__version__",
592
639
  "KEY_SPEC_THREAD_KEYRING",
@@ -658,4 +705,5 @@ __all__ = [
658
705
  "move_key",
659
706
  "new_keyring",
660
707
  "list_keyring",
708
+ "get_keyring_id",
661
709
  ]
@@ -29,6 +29,7 @@ _SYSCALL_NUMBERS = {
29
29
  }
30
30
 
31
31
  # keyctl(2) operations.
32
+ KEYCTL_GET_KEYRING_ID = 0
32
33
  KEYCTL_JOIN_SESSION_KEYRING = 1
33
34
  KEYCTL_UPDATE = 2
34
35
  KEYCTL_REVOKE = 3
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: linux-keyctl
3
- Version: 1.1.0
3
+ Version: 1.2.0
4
4
  Summary: Thin Python interface to the Linux kernel key management system calls
5
5
  Author: Juan Domingo Martín
6
6
  License-Expression: GPL-3.0-or-later
@@ -13,6 +13,7 @@ import os
13
13
  import struct
14
14
  import subprocess
15
15
  import sys
16
+ import threading
16
17
  import time
17
18
  import unittest
18
19
  from unittest import mock
@@ -22,6 +23,7 @@ from linux_keyctl import _syscall
22
23
 
23
24
  SESSION = keyctl.KEY_SPEC_SESSION_KEYRING
24
25
  USER = keyctl.KEY_SPEC_USER_KEYRING
26
+ THREAD = keyctl.KEY_SPEC_THREAD_KEYRING
25
27
 
26
28
 
27
29
  def setUpModule():
@@ -129,6 +131,7 @@ class NamespaceTest(unittest.TestCase):
129
131
  "move_key",
130
132
  "new_keyring",
131
133
  "list_keyring",
134
+ "get_keyring_id",
132
135
  }
133
136
  | {
134
137
  f"KEY_REQKEY_DEFL_{n}"
@@ -174,7 +177,7 @@ class NamespaceTest(unittest.TestCase):
174
177
  self.assertEqual(public, self.EXPECTED - {"__version__"})
175
178
 
176
179
  def test_version(self):
177
- self.assertEqual(keyctl.__version__, "1.1.0")
180
+ self.assertEqual(keyctl.__version__, "1.2.0")
178
181
 
179
182
  def test_no_keyctl_module_shipped(self):
180
183
  src = os.path.join(os.path.dirname(__file__), "..", "src")
@@ -293,6 +296,7 @@ class SignatureTest(unittest.TestCase):
293
296
  "move_key": "(key_id, from_keyring, to_keyring, flags=0)",
294
297
  "join_session_keyring": "(name=None)",
295
298
  "session_to_parent": "()",
299
+ "get_keyring_id": "(key_id, create=False)",
296
300
  }
297
301
 
298
302
  def test_signatures(self):
@@ -381,6 +385,7 @@ class ValidationTest(KeyringTest):
381
385
  (keyctl.search, (SESSION, b"d", bad)),
382
386
  (keyctl.move_key, (1, SESSION, bad)),
383
387
  (keyctl.set_perm, (bad, 0)),
388
+ (keyctl.get_keyring_id, (bad,)),
384
389
  ]:
385
390
  with self.subTest(func=func.__name__, value=bad):
386
391
  with self.assertRaises(OverflowError):
@@ -399,6 +404,20 @@ class ValidationTest(KeyringTest):
399
404
  self.assertEqual(keyctl.set_timeout(key, 2**32 - 1), 0)
400
405
  self.assertEqual(keyctl.set_timeout(key, 0), 0)
401
406
 
407
+ def test_get_keyring_id_create_flag(self):
408
+ for bad in ("yes", None, 1.0, b"\x01"):
409
+ with self.subTest(create=bad):
410
+ with self.assertRaises(TypeError):
411
+ keyctl.get_keyring_id(SESSION, bad)
412
+ cases = [(False, 0), (True, 1), (0, 0), (7, 1), (2**64, 1)]
413
+ with mock.patch.object(_syscall, "keyctl", return_value=5) as call:
414
+ for create, passed in cases:
415
+ with self.subTest(create=create):
416
+ self.assertEqual(keyctl.get_keyring_id(SESSION, create), 5)
417
+ call.assert_called_with(
418
+ _syscall.KEYCTL_GET_KEYRING_ID, SESSION, passed
419
+ )
420
+
402
421
  def test_non_int_id(self):
403
422
  with self.assertRaises(TypeError):
404
423
  keyctl.read_key("1")
@@ -698,6 +717,112 @@ class OtherOperationsTest(KeyringTest):
698
717
  call.assert_called_once_with(_syscall.KEYCTL_SESSION_TO_PARENT)
699
718
 
700
719
 
720
+ class GetKeyringIdTest(KeyringTest):
721
+ def test_session_keyring(self):
722
+ serial = keyctl.get_keyring_id(SESSION)
723
+ self.assertGreater(serial, 0)
724
+ self.assertEqual(keyctl.get_keyring_id(SESSION, True), serial)
725
+ self.assertEqual(keyctl.key_info(serial).description, b"_ses")
726
+ key = self.add(b"lk-gkid-session")
727
+ self.assertIn(key, list(keyctl.list_keyring(serial)))
728
+
729
+ def test_user_keyrings(self):
730
+ uid = os.getuid()
731
+ for spec, name in (
732
+ (USER, f"_uid.{uid}"),
733
+ (keyctl.KEY_SPEC_USER_SESSION_KEYRING, f"_uid_ses.{uid}"),
734
+ ):
735
+ with self.subTest(name=name):
736
+ info = keyctl.key_info(keyctl.get_keyring_id(spec))
737
+ self.assertEqual(info.key_type, keyctl.KEY_TYPE_KEYRING)
738
+ self.assertEqual(info.description, name.encode())
739
+
740
+ def test_ordinary_serial_unchanged(self):
741
+ for serial in (self.add(b"lk-gkid-key"), self.ring(b"lk-gkid-ring")):
742
+ self.assertEqual(keyctl.get_keyring_id(serial), serial)
743
+ self.assertEqual(keyctl.get_keyring_id(serial, True), serial)
744
+
745
+ def test_thread_keyring_created_on_request(self):
746
+ # A new thread has no thread keyring; the one created here is
747
+ # destroyed with the thread.
748
+ outcome = {}
749
+
750
+ def run():
751
+ try:
752
+ keyctl.get_keyring_id(THREAD)
753
+ except OSError as exc:
754
+ outcome["missing"] = exc.errno
755
+ outcome["created"] = keyctl.get_keyring_id(THREAD, True)
756
+ outcome["again"] = keyctl.get_keyring_id(THREAD)
757
+ outcome["info"] = keyctl.key_info(outcome["created"])
758
+
759
+ thread = threading.Thread(target=run)
760
+ thread.start()
761
+ thread.join()
762
+ self.assertEqual(outcome.get("missing"), errno.ENOKEY)
763
+ self.assertGreater(outcome["created"], 0)
764
+ self.assertEqual(outcome["again"], outcome["created"])
765
+ self.assertEqual(outcome["info"].description, b"_tid")
766
+
767
+ def test_create_replaces_user_session_as_session(self):
768
+ # Runs in a child process: it changes the session keyring.
769
+ code = (
770
+ "import os, linux_keyctl as k\n"
771
+ "S = k.KEY_SPEC_SESSION_KEYRING\n"
772
+ "us = k.get_keyring_id(k.KEY_SPEC_USER_SESSION_KEYRING)\n"
773
+ "name = f'_uid_ses.{os.getuid()}'.encode()\n"
774
+ "if k.join_session_keyring(name) != us:\n"
775
+ " raise SystemExit(3)\n"
776
+ "assert k.get_keyring_id(S) == us\n"
777
+ "new = k.get_keyring_id(S, True)\n"
778
+ "assert new != us, new\n"
779
+ "assert k.key_info(new).description == b'_ses'\n"
780
+ "assert k.get_keyring_id(S) == new\n"
781
+ )
782
+ env = dict(os.environ, PYTHONPATH=os.pathsep.join(sys.path))
783
+ result = subprocess.run(
784
+ [sys.executable, "-c", code],
785
+ env=env,
786
+ capture_output=True,
787
+ text=True,
788
+ )
789
+ if result.returncode == 3:
790
+ self.skipTest("cannot join the user-session keyring by name")
791
+ self.assertEqual(result.returncode, 0, result.stderr)
792
+
793
+ def test_errors(self):
794
+ for bad in (0, keyctl.KEY_SPEC_GROUP_KEYRING, -9):
795
+ self.assertErrno(errno.EINVAL, keyctl.get_keyring_id, bad)
796
+ # Only available inside a request-key upcall.
797
+ for spec in (
798
+ keyctl.KEY_SPEC_REQKEY_AUTH_KEY,
799
+ keyctl.KEY_SPEC_REQUESTOR_KEYRING,
800
+ ):
801
+ self.assertErrno(errno.ENOKEY, keyctl.get_keyring_id, spec)
802
+ missing = self.missing_serial()
803
+ self.assertErrno(errno.ENOKEY, keyctl.get_keyring_id, missing, True)
804
+ revoked = self.add(b"lk-gkid-revoked")
805
+ keyctl.revoke(revoked)
806
+ self.assertErrno(errno.EKEYREVOKED, keyctl.get_keyring_id, revoked)
807
+
808
+ def test_needs_search_permission(self):
809
+ # Without POS_SEARCH the key is no longer possessed and the
810
+ # KEY_USR_* bits apply; USR_SETATTR lets the test restore it.
811
+ key = self.add(b"lk-gkid-nosearch")
812
+ keyctl.set_perm(
813
+ key,
814
+ (keyctl.KEY_POS_ALL & ~keyctl.KEY_POS_SEARCH)
815
+ | keyctl.KEY_USR_VIEW
816
+ | keyctl.KEY_USR_SETATTR,
817
+ )
818
+ exc = self.assertErrno(errno.EACCES, keyctl.get_keyring_id, key)
819
+ self.assertIsInstance(exc, PermissionError)
820
+ keyctl.set_perm(key, keyctl.KEY_POS_SEARCH | keyctl.KEY_POS_SETATTR)
821
+ self.assertEqual(keyctl.get_keyring_id(key), key)
822
+ # Restore every bit so tearDown can invalidate the key.
823
+ keyctl.set_perm(key, keyctl.KEY_POS_ALL)
824
+
825
+
701
826
  # --- buffer protocol and backend ---
702
827
 
703
828
 
@@ -766,6 +891,7 @@ class BackendTest(unittest.TestCase):
766
891
  (keyctl.add_key, (b"d", b"v", SESSION)),
767
892
  (keyctl.request_key, (b"d",)),
768
893
  (keyctl.session_to_parent, ()),
894
+ (keyctl.get_keyring_id, (SESSION,)),
769
895
  ]:
770
896
  with self.assertRaises(OSError) as ctx:
771
897
  func(*args)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes