1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
3 ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
5 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; This is the auth-source.el package. It lets users tell Gnus how to
26 ;; authenticate in a single place. Simplicity is the goal. Instead
27 ;; of providing 5000 options, we'll stick to simple, easy to
28 ;; understand options.
30 ;; See the auth.info Info documentation for details.
34 ;; - never decode the backend file unless it's necessary
35 ;; - a more generic way to match backends and search backend contents
36 ;; - absorb netrc.el and simplify it
37 ;; - protect passwords better
38 ;; - allow creating and changing netrc lines (not files) e.g. change a password
42 (require 'password-cache
)
47 (eval-when-compile (require 'cl
))
50 (autoload 'secrets-create-item
"secrets")
51 (autoload 'secrets-delete-item
"secrets")
52 (autoload 'secrets-get-alias
"secrets")
53 (autoload 'secrets-get-attributes
"secrets")
54 (autoload 'secrets-get-secret
"secrets")
55 (autoload 'secrets-list-collections
"secrets")
56 (autoload 'secrets-search-items
"secrets")
58 (autoload 'rfc2104-hash
"rfc2104")
60 (autoload 'plstore-open
"plstore")
61 (autoload 'plstore-find
"plstore")
62 (autoload 'plstore-put
"plstore")
63 (autoload 'plstore-delete
"plstore")
64 (autoload 'plstore-save
"plstore")
65 (autoload 'plstore-get-file
"plstore")
67 (autoload 'epg-make-context
"epg")
68 (autoload 'epg-context-set-passphrase-callback
"epg")
69 (autoload 'epg-decrypt-string
"epg")
70 (autoload 'epg-context-set-armor
"epg")
71 (autoload 'epg-encrypt-string
"epg")
73 (autoload 'help-mode
"help-mode" nil t
)
75 (defvar secrets-enabled
)
77 (defgroup auth-source nil
78 "Authentication sources."
79 :version
"23.1" ;; No Gnus
83 (defcustom auth-source-cache-expiry
7200
84 "How many seconds passwords are cached, or nil to disable
85 expiring. Overrides `password-cache-expiry' through a
89 :type
'(choice (const :tag
"Never" nil
)
90 (const :tag
"All Day" 86400)
91 (const :tag
"2 Hours" 7200)
92 (const :tag
"30 Minutes" 1800)
93 (integer :tag
"Seconds")))
95 ;;; The slots below correspond with the `auth-source-search' spec,
96 ;;; so a backend with :host set, for instance, would match only
97 ;;; searches for that host. Normally they are nil.
98 (defclass auth-source-backend
()
103 :documentation
"The backend type.")
104 (source :initarg
:source
107 :documentation
"The backend source.")
112 :documentation
"The backend host.")
117 :documentation
"The backend user.")
122 :documentation
"The backend protocol.")
125 :documentation
"Internal backend data.")
126 (create-function :initarg
:create-function
130 :documentation
"The create function.")
131 (search-function :initarg
:search-function
135 :documentation
"The search function.")))
137 (defcustom auth-source-protocols
'((imap "imap" "imaps" "143" "993")
138 (pop3 "pop3" "pop" "pop3s" "110" "995")
142 "List of authentication protocols and their names"
145 :version
"23.2" ;; No Gnus
146 :type
'(repeat :tag
"Authentication Protocols"
147 (cons :tag
"Protocol Entry"
148 (symbol :tag
"Protocol")
150 (string :tag
"Name")))))
152 ;;; generate all the protocols in a format Customize can use
153 ;;; TODO: generate on the fly from auth-source-protocols
154 (defconst auth-source-protocols-customize
156 (let ((p (car-safe a
)))
158 :tag
(upcase (symbol-name p
))
160 auth-source-protocols
))
162 (defvar auth-source-creation-defaults nil
163 "Defaults for creating token values. Usually let-bound.")
165 (defvar auth-source-creation-prompts nil
166 "Default prompts for token values. Usually let-bound.")
168 (make-obsolete 'auth-source-hide-passwords nil
"Emacs 24.1")
170 (defcustom auth-source-save-behavior
'ask
171 "If set, auth-source will respect it for save behavior."
173 :version
"23.2" ;; No Gnus
175 :tag
"auth-source new token save behavior"
176 (const :tag
"Always save" t
)
177 (const :tag
"Never save" nil
)
178 (const :tag
"Ask" ask
)))
180 ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car (symbol-value 'epa-file-auto-mode-alist-entry)) "\\.gpg\\'") never) (t gpg)))
181 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
183 (defcustom auth-source-netrc-use-gpg-tokens
'never
184 "Set this to tell auth-source when to create GPG password
185 tokens in netrc files. It's either an alist or `never'.
186 Note that if EPA/EPG is not available, this should NOT be used."
188 :version
"23.2" ;; No Gnus
190 (const :tag
"Always use GPG password tokens" (t gpg
))
191 (const :tag
"Never use GPG password tokens" never
)
192 (repeat :tag
"Use a lookup list"
194 (choice :tag
"Matcher"
195 (const :tag
"Match anything" t
)
196 (const :tag
"The EPA encrypted file extensions"
197 ,(if (boundp 'epa-file-auto-mode-alist-entry
)
199 'epa-file-auto-mode-alist-entry
))
201 (regexp :tag
"Regular expression"))
202 (choice :tag
"What to do"
203 (const :tag
"Save GPG-encrypted password tokens" gpg
)
204 (const :tag
"Don't encrypt tokens" never
))))))
206 (defvar auth-source-magic
"auth-source-magic ")
208 (defcustom auth-source-do-cache t
209 "Whether auth-source should cache information with `password-cache'."
211 :version
"23.2" ;; No Gnus
214 (defcustom auth-source-debug nil
215 "Whether auth-source should log debug messages.
217 If the value is nil, debug messages are not logged.
219 If the value is t, debug messages are logged with `message'. In
220 that case, your authentication data will be in the clear (except
223 If the value is a function, debug messages are logged by calling
224 that function using the same arguments as `message'."
226 :version
"23.2" ;; No Gnus
228 :tag
"auth-source debugging mode"
229 (const :tag
"Log using `message' to the *Messages* buffer" t
)
230 (const :tag
"Log all trivia with `message' to the *Messages* buffer"
232 (function :tag
"Function that takes arguments like `message'")
233 (const :tag
"Don't log anything" nil
)))
235 (defcustom auth-sources
'("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
236 "List of authentication sources.
238 The default will get login and password information from
239 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
240 packages to be encrypted. If that file doesn't exist, it will
241 try the unencrypted version \"~/.authinfo\" and the famous
244 See the auth.info manual for details.
246 Each entry is the authentication type with optional properties.
248 It's best to customize this with `M-x customize-variable' because the choices
249 can get pretty complex."
251 :version
"24.1" ;; No Gnus
252 :type
`(repeat :tag
"Authentication Sources"
254 (string :tag
"Just a file")
255 (const :tag
"Default Secrets API Collection" 'default
)
256 (const :tag
"Login Secrets API Collection" "secrets:Login")
257 (const :tag
"Temp Secrets API Collection" "secrets:session")
258 (list :tag
"Source definition"
259 (const :format
"" :value
:source
)
260 (choice :tag
"Authentication backend choice"
261 (string :tag
"Authentication Source (file)")
263 :tag
"Secret Service API/KWallet/GNOME Keyring"
264 (const :format
"" :value
:secrets
)
265 (choice :tag
"Collection to use"
266 (string :tag
"Collection name")
267 (const :tag
"Default" 'default
)
268 (const :tag
"Login" "Login")
270 :tag
"Temporary" "session"))))
271 (repeat :tag
"Extra Parameters" :inline t
272 (choice :tag
"Extra parameter"
275 (const :format
"" :value
:host
)
276 (choice :tag
"Host (machine) choice"
279 :tag
"Regular expression")))
282 (const :format
"" :value
:port
)
286 ,@auth-source-protocols-customize
))
287 (list :tag
"User" :inline t
288 (const :format
"" :value
:user
)
290 :tag
"Personality/Username"
295 (defcustom auth-source-gpg-encrypt-to t
296 "List of recipient keys that `authinfo.gpg' encrypted to.
297 If the value is not a list, symmetric encryption will be used."
299 :version
"24.1" ;; No Gnus
300 :type
'(choice (const :tag
"Symmetric encryption" t
)
301 (repeat :tag
"Recipient public keys"
302 (string :tag
"Recipient public key"))))
304 ;; temp for debugging
305 ;; (unintern 'auth-source-protocols)
306 ;; (unintern 'auth-sources)
307 ;; (customize-variable 'auth-sources)
308 ;; (setq auth-sources nil)
309 ;; (format "%S" auth-sources)
310 ;; (customize-variable 'auth-source-protocols)
311 ;; (setq auth-source-protocols nil)
312 ;; (format "%S" auth-source-protocols)
313 ;; (auth-source-pick nil :host "a" :port 'imap)
314 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
315 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
316 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
317 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
318 ;; (auth-source-protocol-defaults 'imap)
320 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
321 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
322 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
323 (defun auth-source-do-debug (&rest msg
)
324 (when auth-source-debug
325 (apply 'auth-source-do-warn msg
)))
327 (defun auth-source-do-trivia (&rest msg
)
328 (when (or (eq auth-source-debug
'trivia
)
329 (functionp auth-source-debug
))
330 (apply 'auth-source-do-warn msg
)))
332 (defun auth-source-do-warn (&rest msg
)
334 ;; set logger to either the function in auth-source-debug or 'message
335 ;; note that it will be 'message if auth-source-debug is nil
336 (if (functionp auth-source-debug
)
342 ;;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
343 (defun auth-source-read-char-choice (prompt choices
)
344 "Read one of CHOICES by `read-char-choice', or `read-char'.
345 `dropdown-list' support is disabled because it doesn't work reliably.
346 Only one of CHOICES will be returned. The PROMPT is augmented
347 with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
349 (let* ((prompt-choices
350 (apply 'concat
(loop for c in choices
351 collect
(format "%c/" c
))))
352 (prompt-choices (concat "[" (substring prompt-choices
0 -
1) "] "))
353 (full-prompt (concat prompt prompt-choices
))
356 (while (not (memq k choices
))
358 ((fboundp 'read-char-choice
)
359 (read-char-choice full-prompt choices
))
360 (t (message "%s" full-prompt
)
361 (setq k
(read-char))))))
364 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
365 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
366 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
367 ;; (:source (:secrets "session") :host t :port t :user "joe")
368 ;; (:source (:secrets "Login") :host t :port t)
369 ;; (:source "~/.authinfo.gpg" :host t :port t)))
371 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
372 ;; (:source (:secrets "session") :host t :port t :user "joe")
373 ;; (:source (:secrets "Login") :host t :port t)
376 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
378 ;; (auth-source-backend-parse "myfile.gpg")
379 ;; (auth-source-backend-parse 'default)
380 ;; (auth-source-backend-parse "secrets:Login")
382 (defun auth-source-backend-parse (entry)
383 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
384 (auth-source-backend-parse-parameters
387 ;; take 'default and recurse to get it as a Secrets API default collection
388 ;; matching any user, host, and protocol
390 (auth-source-backend-parse '(:source
(:secrets default
))))
391 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
392 ;; matching any user, host, and protocol
393 ((and (stringp entry
) (string-match "^secrets:\\(.+\\)" entry
))
394 (auth-source-backend-parse `(:source
(:secrets
,(match-string 1 entry
)))))
395 ;; take just a file name and recurse to get it as a netrc file
396 ;; matching any user, host, and protocol
398 (auth-source-backend-parse `(:source
,entry
)))
400 ;; a file name with parameters
401 ((stringp (plist-get entry
:source
))
402 (if (equal (file-name-extension (plist-get entry
:source
)) "plist")
404 (plist-get entry
:source
)
405 :source
(plist-get entry
:source
)
407 :search-function
'auth-source-plstore-search
408 :create-function
'auth-source-plstore-create
409 :data
(plstore-open (plist-get entry
:source
)))
411 (plist-get entry
:source
)
412 :source
(plist-get entry
:source
)
414 :search-function
'auth-source-netrc-search
415 :create-function
'auth-source-netrc-create
)))
417 ;; the Secrets API. We require the package, in order to have a
418 ;; defined value for `secrets-enabled'.
420 (not (null (plist-get entry
:source
))) ; the source must not be nil
421 (listp (plist-get entry
:source
)) ; and it must be a list
422 (require 'secrets nil t
) ; and we must load the Secrets API
423 secrets-enabled
) ; and that API must be enabled
425 ;; the source is either the :secrets key in ENTRY or
426 ;; if that's missing or nil, it's "session"
427 (let ((source (or (plist-get (plist-get entry
:source
) :secrets
)
430 ;; if the source is a symbol, we look for the alias named so,
431 ;; and if that alias is missing, we use "Login"
432 (when (symbolp source
)
433 (setq source
(or (secrets-get-alias (symbol-name source
))
436 (if (featurep 'secrets
)
438 (format "Secrets API (%s)" source
)
441 :search-function
'auth-source-secrets-search
442 :create-function
'auth-source-secrets-create
)
444 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry
)
446 (format "Ignored Secrets API (%s)" source
)
453 "auth-source-backend-parse: invalid backend spec: %S" entry
)
459 (defun auth-source-backend-parse-parameters (entry backend
)
460 "Fills in the extra auth-source-backend parameters of ENTRY.
461 Using the plist ENTRY, get the :host, :port, and :user search
463 (let ((entry (if (stringp entry
)
467 (when (setq val
(plist-get entry
:host
))
468 (oset backend host val
))
469 (when (setq val
(plist-get entry
:user
))
470 (oset backend user val
))
471 (when (setq val
(plist-get entry
:port
))
472 (oset backend port val
)))
475 ;; (mapcar 'auth-source-backend-parse auth-sources)
477 (defun* auth-source-search
(&rest spec
478 &key type max host user port secret
479 require create delete
481 "Search or modify authentication backends according to SPEC.
483 This function parses `auth-sources' for matches of the SPEC
484 plist. It can optionally create or update an authentication
485 token if requested. A token is just a standard Emacs property
486 list with a :secret property that can be a function; all the
487 other properties will always hold scalar values.
489 Typically the :secret property, if present, contains a password.
491 Common search keys are :max, :host, :port, and :user. In
492 addition, :create specifies how tokens will be or created.
493 Finally, :type can specify which backend types you want to check.
495 A string value is always matched literally. A symbol is matched
496 as its string value, literally. All the SPEC values can be
497 single values (symbol or string) or lists thereof (in which case
498 any of the search terms matches).
500 :create t means to create a token if possible.
502 A new token will be created if no matching tokens were found.
503 The new token will have only the keys the backend requires. For
504 the netrc backend, for instance, that's the user, host, and
509 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
510 (A . \"default A\"))))
511 (auth-source-search :host \"mine\" :type 'netrc :max 1
512 :P \"pppp\" :Q \"qqqq\"
517 \"Search for any entry matching host 'mine' in backends of type
518 'netrc', maximum one result.
520 Create a new entry if you found none. The netrc backend will
521 automatically require host, user, and port. The host will be
522 'mine'. We prompt for the user with default 'defaultUser' and
523 for the port without a default. We will not prompt for A, Q,
524 or P. The resulting token will only have keys user, host, and
527 :create '(A B C) also means to create a token if possible.
529 The behavior is like :create t but if the list contains any
530 parameter, that parameter will be required in the resulting
531 token. The value for that parameter will be obtained from the
532 search parameters or from user input. If any queries are needed,
533 the alist `auth-source-creation-defaults' will be checked for the
534 default value. If the user, host, or port are missing, the alist
535 `auth-source-creation-prompts' will be used to look up the
536 prompts IN THAT ORDER (so the 'user prompt will be queried first,
537 then 'host, then 'port, and finally 'secret). Each prompt string
538 can use %u, %h, and %p to show the user, host, and port.
542 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
543 (A . \"default A\")))
544 (auth-source-creation-prompts
545 '((password . \"Enter IMAP password for %h:%p: \"))))
546 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
547 :P \"pppp\" :Q \"qqqq\"
552 \"Search for any entry matching host 'nonesuch'
553 or 'twosuch' in backends of type 'netrc', maximum one result.
555 Create a new entry if you found none. The netrc backend will
556 automatically require host, user, and port. The host will be
557 'nonesuch' and Q will be 'qqqq'. We prompt for the password
558 with the shown prompt. We will not prompt for Q. The resulting
559 token will have keys user, host, port, A, B, and Q. It will not
560 have P with any value, even though P is used in the search to
561 find only entries that have P set to 'pppp'.\"
563 When multiple values are specified in the search parameter, the
564 user is prompted for which one. So :host (X Y Z) would ask the
565 user to choose between X, Y, and Z.
567 This creation can fail if the search was not specific enough to
568 create a new token (it's up to the backend to decide that). You
569 should `catch' the backend-specific error as usual. Some
570 backends (netrc, at least) will prompt the user rather than throw
573 :require (A B C) means that only results that contain those
574 tokens will be returned. Thus for instance requiring :secret
575 will ensure that any results will actually have a :secret
578 :delete t means to delete any found entries. nil by default.
579 Use `auth-source-delete' in ELisp code instead of calling
580 `auth-source-search' directly with this parameter.
582 :type (X Y Z) will check only those backend types. 'netrc and
583 'secrets are the only ones supported right now.
585 :max N means to try to return at most N items (defaults to 1).
586 When 0 the function will return just t or nil to indicate if any
587 matches were found. More than N items may be returned, depending
588 on the search and the backend.
590 :host (X Y Z) means to match only hosts X, Y, or Z according to
591 the match rules above. Defaults to t.
593 :user (X Y Z) means to match only users X, Y, or Z according to
594 the match rules above. Defaults to t.
596 :port (P Q R) means to match only protocols P, Q, or R.
599 :K (V1 V2 V3) for any other key K will match values V1, V2, or
600 V3 (note the match rules above).
602 The return value is a list with at most :max tokens. Each token
603 is a plist with keys :backend :host :port :user, plus any other
604 keys provided by the backend (notably :secret). But note the
605 exception for :max 0, which see above.
607 The token can hold a :save-function key. If you call that, the
608 user will be prompted to save the data to the backend. You can't
609 request that this should happen right after creation, because
610 `auth-source-search' has no way of knowing if the token is
611 actually useful. So the caller must arrange to call this function.
613 The token's :secret key can hold a function. In that case you
614 must call it to obtain the actual value."
615 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources
))
617 (ignored-keys '(:require
:create
:delete
:max
))
618 (keys (loop for i below
(length spec
) by
2
619 unless
(memq (nth i spec
) ignored-keys
)
620 collect
(nth i spec
)))
621 (cached (auth-source-remembered-p spec
))
622 ;; note that we may have cached results but found is still nil
623 ;; (there were no results from the search)
624 (found (auth-source-recall spec
))
625 filtered-backends accessor-key backend
)
627 (if (and cached auth-source-do-cache
)
628 (auth-source-do-debug
629 "auth-source-search: found %d CACHED results matching %S"
633 (or (eq t create
) (listp create
)) t
634 "Invalid auth-source :create parameter (must be t or a list): %s %s")
638 "Invalid auth-source :require parameter (must be a list): %s")
640 (setq filtered-backends
(copy-sequence backends
))
641 (dolist (backend backends
)
643 ;; ignore invalid slots
644 (condition-case signal
645 (unless (eval `(auth-source-search-collection
647 (oref backend
,key
)))
648 (setq filtered-backends
(delq backend filtered-backends
))
650 (invalid-slot-name))))
652 (auth-source-do-trivia
653 "auth-source-search: found %d backends matching %S"
654 (length filtered-backends
) spec
)
656 ;; (debug spec "filtered" filtered-backends)
657 ;; First go through all the backends without :create, so we can
659 (setq found
(auth-source-search-backends filtered-backends
663 ;; create is always nil here
667 (auth-source-do-debug
668 "auth-source-search: found %d results (max %d) matching %S"
669 (length found
) max spec
)
671 ;; If we didn't find anything, then we allow the backend(s) to
672 ;; create the entries.
675 (setq found
(auth-source-search-backends filtered-backends
681 (auth-source-do-debug
682 "auth-source-search: CREATED %d results (max %d) matching %S"
683 (length found
) max spec
))
685 ;; note we remember the lack of result too, if it's applicable
686 (when auth-source-do-cache
687 (auth-source-remember spec found
)))
691 (defun auth-source-search-backends (backends spec max create delete require
)
693 (dolist (backend backends
)
694 (when (> max
(length matches
)) ; when we need more matches...
695 (let* ((bmatches (apply
696 (slot-value backend
'search-function
)
698 ;; note we're overriding whatever the spec
699 ;; has for :require, :create, and :delete
705 (auth-source-do-trivia
706 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
707 (length bmatches
) max
708 (slot-value backend
:type
)
709 (slot-value backend
:source
)
711 (setq matches
(append matches bmatches
))))))
714 ;;; (auth-source-search :max 1)
715 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
716 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
717 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
719 (defun* auth-source-delete
(&rest spec
722 "Delete entries from the authentication backends according to SPEC.
723 Calls `auth-source-search' with the :delete property in SPEC set to t.
724 The backend may not actually delete the entries.
726 Returns the deleted entries."
727 (auth-source-search (plist-put spec
:delete t
)))
729 (defun auth-source-search-collection (collection value
)
730 "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
731 (when (and (atom collection
) (not (eq t collection
)))
732 (setq collection
(list collection
)))
734 ;; (debug :collection collection :value value)
735 (or (eq collection t
)
737 (equal collection value
)
738 (member value collection
)))
740 (defvar auth-source-netrc-cache nil
)
742 (defun auth-source-forget-all-cached ()
743 "Forget all cached auth-source data."
745 (loop for sym being the symbols of password-data
746 ;; when the symbol name starts with auth-source-magic
747 when
(string-match (concat "^" auth-source-magic
)
750 do
(password-cache-remove (symbol-name sym
)))
751 (setq auth-source-netrc-cache nil
))
753 (defun auth-source-format-cache-entry (spec)
754 "Format SPEC entry to put it in the password cache."
755 (concat auth-source-magic
(format "%S" spec
)))
757 (defun auth-source-remember (spec found
)
758 "Remember FOUND search results for SPEC."
759 (let ((password-cache-expiry auth-source-cache-expiry
))
761 (auth-source-format-cache-entry spec
) found
)))
763 (defun auth-source-recall (spec)
764 "Recall FOUND search results for SPEC."
765 (password-read-from-cache (auth-source-format-cache-entry spec
)))
767 (defun auth-source-remembered-p (spec)
768 "Check if SPEC is remembered."
770 (auth-source-format-cache-entry spec
)))
772 (defun auth-source-forget (spec)
773 "Forget any cached data matching SPEC exactly.
775 This is the same SPEC you passed to `auth-source-search'.
776 Returns t or nil for forgotten or not found."
777 (password-cache-remove (auth-source-format-cache-entry spec
)))
779 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
781 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
782 ;;; (auth-source-remembered-p '(:host "wedd"))
783 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
784 ;;; (auth-source-remembered-p '(:host "xedd"))
785 ;;; (auth-source-remembered-p '(:host "zedd"))
786 ;;; (auth-source-recall '(:host "xedd"))
787 ;;; (auth-source-recall '(:host t))
788 ;;; (auth-source-forget+ :host t)
790 (defun* auth-source-forget
+ (&rest spec
&allow-other-keys
)
791 "Forget any cached data matching SPEC. Returns forgotten count.
793 This is not a full `auth-source-search' spec but works similarly.
794 For instance, \(:host \"myhost\" \"yourhost\") would find all the
795 cached data that was found with a search for those two hosts,
796 while \(:host t) would find all host entries."
799 (loop for sym being the symbols of password-data
800 ;; when the symbol name matches with auth-source-magic
801 when
(and (setq sname
(symbol-name sym
))
802 (string-match (concat "^" auth-source-magic
"\\(.+\\)")
804 ;; and the spec matches what was stored in the cache
805 (auth-source-specmatchp spec
(read (match-string 1 sname
))))
808 (password-cache-remove sname
)
812 (defun auth-source-specmatchp (spec stored
)
813 (let ((keys (loop for i below
(length spec
) by
2
814 collect
(nth i spec
))))
817 (unless (auth-source-search-collection (plist-get stored key
)
818 (plist-get spec key
))
822 ;;; (auth-source-pick-first-password :host "z.lifelogs.com")
823 ;;; (auth-source-pick-first-password :port "imap")
824 (defun auth-source-pick-first-password (&rest spec
)
825 "Pick the first secret found from applying SPEC to `auth-source-search'."
826 (let* ((result (nth 0 (apply 'auth-source-search
(plist-put spec
:max
1))))
827 (secret (plist-get result
:secret
)))
829 (if (functionp secret
)
833 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
834 (defun auth-source-format-prompt (prompt alist
)
835 "Format PROMPT using %x (for any character x) specifiers in ALIST."
837 (let ((c (nth 0 cell
))
840 (setq prompt
(replace-regexp-in-string (format "%%%c" c
)
845 (defun auth-source-ensure-strings (values)
846 (unless (listp values
)
847 (setq values
(list values
)))
848 (mapcar (lambda (value)
854 ;;; Backend specific parsing: netrc/authinfo backend
856 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
857 (defun* auth-source-netrc-parse
(&rest
859 &key file max host user port delete require
861 "Parse FILE and return a list of all entries in the file.
862 Note that the MAX parameter is used so we can exit the parse early."
864 ;; We got already parsed contents; just return it.
866 (when (file-exists-p file
)
867 (setq port
(auth-source-ensure-strings port
))
869 (let* ((tokens '("machine" "host" "default" "login" "user"
870 "password" "account" "macdef" "force"
872 (max (or max
5000)) ; sanity check: default to stop at 5K
874 (cached (cdr-safe (assoc file auth-source-netrc-cache
)))
875 (cached-mtime (plist-get cached
:mtime
))
876 (cached-secrets (plist-get cached
:secret
))
877 alist elem result pair
)
879 (if (and (functionp cached-secrets
)
881 (nth 5 (file-attributes file
))))
883 (auth-source-do-trivia
884 "auth-source-netrc-parse: using CACHED file data for %s"
886 (insert (funcall cached-secrets
)))
887 (insert-file-contents file
)
888 ;; cache all netrc files (used to be just .gpg files)
889 ;; Store the contents of the file heavily encrypted in memory.
890 ;; (note for the irony-impaired: they are just obfuscated)
891 (aput 'auth-source-netrc-cache file
892 (list :mtime
(nth 5 (file-attributes file
))
893 :secret
(lexical-let ((v (mapcar '1+ (buffer-string))))
894 (lambda () (apply 'string
(mapcar '1- v
)))))))
895 (goto-char (point-min))
896 ;; Go through the file, line by line.
897 (while (and (not (eobp))
900 (narrow-to-region (point) (point-at-eol))
901 ;; For each line, get the tokens and values.
903 (skip-chars-forward "\t ")
904 ;; Skip lines that begin with a "#".
905 (if (eq (char-after) ?
#)
906 (goto-char (point-max))
909 (if (= (following-char) ?
\")
910 (read (current-buffer))
912 (point) (progn (skip-chars-forward "^\t ")
915 ((equal elem
"macdef")
916 ;; We skip past the macro definition.
918 (while (and (zerop (forward-line 1))
920 (narrow-to-region (point) (point)))
921 ((member elem tokens
)
922 ;; Tokens that don't have a following value are ignored,
924 (when (and pair
(or (cdr pair
)
925 (equal (car pair
) "default")))
927 (setq pair
(list elem
)))
929 ;; Values that haven't got a preceding token are ignored.
933 (setq pair nil
)))))))
937 (auth-source-search-collection
940 (aget alist
"machine")
943 (auth-source-search-collection
947 (aget alist
"account")
950 (auth-source-search-collection
954 (aget alist
"protocol")
957 ;; the required list of keys is nil, or
959 ;; every element of require is in the normalized list
960 (let ((normalized (nth 0 (auth-source-netrc-normalize
961 (list alist
) file
))))
962 (loop for req in require
963 always
(plist-get normalized req
)))))
965 (push (nreverse alist
) result
)
966 ;; to delete a line, we just comment it out
968 (goto-char (point-min))
977 (when auth-source-gpg-encrypt-to
978 ;; (see bug#7487) making `epa-file-encrypt-to' local to
979 ;; this buffer lets epa-file skip the key selection query
980 ;; (see the `local-variable-p' check in
981 ;; `epa-file-write-region').
982 (unless (local-variable-p 'epa-file-encrypt-to
(current-buffer))
983 (make-local-variable 'epa-file-encrypt-to
))
984 (if (listp auth-source-gpg-encrypt-to
)
985 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to
)))
987 ;; ask AFTER we've successfully opened the file
988 (when (y-or-n-p (format "Save file %s? (%d deletions)"
990 (write-region (point-min) (point-max) file nil
'silent
)
991 (auth-source-do-debug
992 "auth-source-netrc-parse: modified %d lines in %s"
995 (nreverse result
))))))
997 (defvar auth-source-passphrase-alist nil
)
999 (defun auth-source-token-passphrase-callback-function (context key-id file
)
1000 (let* ((file (file-truename file
))
1001 (entry (assoc file auth-source-passphrase-alist
))
1003 ;; return the saved passphrase, calling a function if needed
1004 (or (copy-sequence (if (functionp (cdr entry
))
1005 (funcall (cdr entry
))
1009 (setq entry
(list file
))
1010 (push entry auth-source-passphrase-alist
))
1013 (format "Passphrase for %s tokens: " file
)
1015 (setcdr entry
(lexical-let ((p (copy-sequence passphrase
)))
1019 ;; (auth-source-epa-extract-gpg-token "gpg:LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tClZlcnNpb246IEdudVBHIHYxLjQuMTEgKEdOVS9MaW51eCkKCmpBMEVBd01DT25qMjB1ak9rZnRneVI3K21iNm9aZWhuLzRad3cySkdlbnVaKzRpeEswWDY5di9icDI1U1dsQT0KPS9yc2wKLS0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo=" "~/.netrc")
1020 (defun auth-source-epa-extract-gpg-token (secret file
)
1021 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1022 FILE is the file from which we obtained this token."
1023 (when (string-match "^gpg:\\(.+\\)" secret
)
1024 (setq secret
(base64-decode-string (match-string 1 secret
))))
1025 (let ((context (epg-make-context 'OpenPGP
))
1027 (epg-context-set-passphrase-callback
1029 (cons #'auth-source-token-passphrase-callback-function
1031 (epg-decrypt-string context secret
)))
1033 ;; (insert (auth-source-epa-make-gpg-token "mysecret" "~/.netrc"))
1034 (defun auth-source-epa-make-gpg-token (secret file
)
1035 (let ((context (epg-make-context 'OpenPGP
))
1036 (pp-escape-newlines nil
)
1038 (epg-context-set-armor context t
)
1039 (epg-context-set-passphrase-callback
1041 (cons #'auth-source-token-passphrase-callback-function
1043 (setq cipher
(epg-encrypt-string context secret nil
))
1046 (base64-encode-region (point-min) (point-max) t
)
1047 (concat "gpg:" (buffer-substring-no-properties
1051 (defun auth-source-netrc-normalize (alist filename
)
1052 (mapcar (lambda (entry)
1054 (while (setq item
(pop entry
))
1055 (let ((k (car item
))
1058 ;; apply key aliases
1059 (setq k
(cond ((member k
'("machine")) "host")
1060 ((member k
'("login" "account")) "user")
1061 ((member k
'("protocol")) "port")
1062 ((member k
'("password")) "secret")
1065 ;; send back the secret in a function (lexical binding)
1066 (when (equal k
"secret")
1067 (setq v
(lexical-let ((lexv v
)
1068 (token-decoder nil
))
1069 (when (string-match "^gpg:" lexv
)
1070 ;; it's a GPG token: create a token decoder
1071 ;; which unsets itself once
1075 (auth-source-epa-extract-gpg-token
1078 (setq token-decoder nil
)))))
1081 (setq lexv
(funcall token-decoder lexv
)))
1083 (setq ret
(plist-put ret
1084 (intern (concat ":" k
))
1089 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
1090 ;;; (funcall secret)
1092 (defun* auth-source-netrc-search
(&rest
1094 &key backend require create delete
1095 type max host user port
1097 "Given a property list SPEC, return search matches from the :backend.
1098 See `auth-source-search' for details on SPEC."
1099 ;; just in case, check that the type is correct (null or same as the backend)
1100 (assert (or (null type
) (eq type
(oref backend type
)))
1101 t
"Invalid netrc search: %s %s")
1103 (let ((results (auth-source-netrc-normalize
1104 (auth-source-netrc-parse
1108 :file
(oref backend source
)
1112 (oref backend source
))))
1114 ;; if we need to create an entry AND none were found to match
1118 ;; create based on the spec and record the value
1120 ;; if the user did not want to create the entry
1121 ;; in the file, it will be returned
1122 (apply (slot-value backend
'create-function
) spec
)
1123 ;; if not, we do the search again without :create
1124 ;; to get the updated data.
1126 ;; the result will be returned, even if the search fails
1127 (apply 'auth-source-netrc-search
1128 (plist-put spec
:create nil
)))))
1131 (defun auth-source-netrc-element-or-first (v)
1136 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1137 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1139 (defun* auth-source-netrc-create
(&rest spec
1141 secret host user port create
1143 (let* ((base-required '(host user port secret
))
1144 ;; we know (because of an assertion in auth-source-search) that the
1145 ;; :create parameter is either t or a list (which includes nil)
1146 (create-extra (if (eq t create
) nil create
))
1147 (current-data (car (auth-source-search :max
1
1150 (required (append base-required create-extra
))
1151 (file (oref backend source
))
1153 ;; `valist' is an alist
1155 ;; `artificial' will be returned if no creation is needed
1158 ;; only for base required elements (defined as function parameters):
1159 ;; fill in the valist with whatever data we may have from the search
1160 ;; we complete the first value if it's a list and use the value otherwise
1161 (dolist (br base-required
)
1162 (when (symbol-value br
)
1163 (let ((br-choice (cond
1164 ;; all-accepting choice (predicate is t)
1165 ((eq t
(symbol-value br
)) nil
)
1166 ;; just the value otherwise
1167 (t (symbol-value br
)))))
1169 (aput 'valist br br-choice
)))))
1171 ;; for extra required elements, see if the spec includes a value for them
1172 (dolist (er create-extra
)
1173 (let ((name (concat ":" (symbol-name er
)))
1174 (keys (loop for i below
(length spec
) by
2
1175 collect
(nth i spec
))))
1177 (when (equal (symbol-name k
) name
)
1178 (aput 'valist er
(plist-get spec k
))))))
1180 ;; for each required element
1181 (dolist (r required
)
1182 (let* ((data (aget valist r
))
1183 ;; take the first element if the data is a list
1184 (data (or (auth-source-netrc-element-or-first data
)
1185 (plist-get current-data
1186 (intern (format ":%s" r
) obarray
))))
1187 ;; this is the default to be offered
1188 (given-default (aget auth-source-creation-defaults r
))
1189 ;; the default supplementals are simple:
1190 ;; for the user, try `given-default' and then (user-login-name);
1191 ;; otherwise take `given-default'
1193 ((and (not given-default
) (eq r
'user
))
1196 (printable-defaults (list
1199 (auth-source-netrc-element-or-first
1200 (aget valist
'user
))
1201 (plist-get artificial
:user
)
1205 (auth-source-netrc-element-or-first
1206 (aget valist
'host
))
1207 (plist-get artificial
:host
)
1211 (auth-source-netrc-element-or-first
1212 (aget valist
'port
))
1213 (plist-get artificial
:port
)
1215 (prompt (or (aget auth-source-creation-prompts r
)
1217 (secret "%p password for %u@%h: ")
1218 (user "%p user name for %h: ")
1219 (host "%p host name for user %u: ")
1220 (port "%p port for %u@%h: "))
1221 (format "Enter %s (%%u@%%h:%%p): " r
)))
1222 (prompt (auth-source-format-prompt
1224 `((?u
,(aget printable-defaults
'user
))
1225 (?h
,(aget printable-defaults
'host
))
1226 (?p
,(aget printable-defaults
'port
))))))
1228 ;; Store the data, prompting for the password if needed.
1231 ;; Special case prompt for passwords.
1232 ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car (symbol-value 'epa-file-auto-mode-alist-entry)) "\\.gpg\\'") nil) (t gpg)))
1233 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1234 (let* ((ep (format "Use GPG password tokens in %s?" file
))
1237 ((eq auth-source-netrc-use-gpg-tokens
'never
)
1239 ((listp auth-source-netrc-use-gpg-tokens
)
1240 (let ((check (copy-sequence
1241 auth-source-netrc-use-gpg-tokens
))
1244 (setq item
(pop check
))
1245 (when (or (eq (car item
) t
)
1246 (string-match (car item
) file
))
1247 (setq ret
(cdr item
))
1248 (setq check nil
)))))
1250 (plain (or (eval default
) (read-passwd prompt
))))
1251 ;; ask if we don't know what to do (in which case
1252 ;; auth-source-netrc-use-gpg-tokens must be a list)
1254 (setq gpg-encrypt
(if (y-or-n-p ep
) 'gpg
'never
))
1255 ;; TODO: save the defcustom now? or ask?
1256 (setq auth-source-netrc-use-gpg-tokens
1257 (cons `(,file
,gpg-encrypt
)
1258 auth-source-netrc-use-gpg-tokens
)))
1259 (if (eq gpg-encrypt
'gpg
)
1260 (auth-source-epa-make-gpg-token plain file
)
1262 (if (stringp default
)
1263 (read-string (if (string-match ": *\\'" prompt
)
1264 (concat (substring prompt
0 (match-beginning 0))
1265 " (default " default
"): ")
1266 (concat prompt
"(default " default
") "))
1271 (setq artificial
(plist-put artificial
1272 (intern (concat ":" (symbol-name r
)))
1274 (lexical-let ((data data
))
1278 ;; When r is not an empty string...
1279 (when (and (stringp data
)
1280 (< 0 (length data
)))
1281 ;; this function is not strictly necessary but I think it
1282 ;; makes the code clearer -tzz
1283 (let ((printer (lambda ()
1284 ;; append the key (the symbol name of r)
1285 ;; and the value in r
1288 (if (zerop (length add
)) "" " ")
1289 ;; remap auth-source tokens to netrc
1294 (port "port") ; redundant but clearer
1295 (t (symbol-name r
)))
1296 (if (string-match "[\"# ]" data
)
1299 (setq add
(concat add
(funcall printer
)))))))
1304 (lexical-let ((file file
)
1306 (lambda () (auth-source-netrc-saver file add
))))
1310 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1311 (defun auth-source-netrc-saver (file add
)
1312 "Save a line ADD in FILE, prompting along the way.
1313 Respects `auth-source-save-behavior'. Uses
1314 `auth-source-netrc-cache' to avoid prompting more than once."
1315 (let* ((key (format "%s %s" file
(rfc2104-hash 'md5
64 16 file add
)))
1316 (cached (assoc key auth-source-netrc-cache
)))
1319 (auth-source-do-trivia
1320 "auth-source-netrc-saver: found previous run for key %s, returning"
1323 (when (file-exists-p file
)
1324 (insert-file-contents file
))
1325 (when auth-source-gpg-encrypt-to
1326 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1327 ;; this buffer lets epa-file skip the key selection query
1328 ;; (see the `local-variable-p' check in
1329 ;; `epa-file-write-region').
1330 (unless (local-variable-p 'epa-file-encrypt-to
(current-buffer))
1331 (make-local-variable 'epa-file-encrypt-to
))
1332 (if (listp auth-source-gpg-encrypt-to
)
1333 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to
)))
1334 ;; we want the new data to be found first, so insert at beginning
1335 (goto-char (point-min))
1337 ;; Ask AFTER we've successfully opened the file.
1338 (let ((prompt (format "Save auth info to file %s? " file
))
1339 (done (not (eq auth-source-save-behavior
'ask
)))
1340 (bufname "*auth-source Help*")
1343 (setq k
(auth-source-read-char-choice prompt
'(?y ?n ?N ?e ??
)))
1347 (with-output-to-temp-buffer bufname
1349 (concat "(y)es, save\n"
1350 "(n)o but use the info\n"
1351 "(N)o and don't ask to save again\n"
1353 "(?) for help as you can see.\n"))
1354 ;; Why? Doesn't with-output-to-temp-buffer already do
1355 ;; the exact same thing anyway? --Stef
1356 (set-buffer standard-output
)
1363 (customize-save-variable 'auth-source-save-behavior nil
))
1364 (?e
(setq add
(read-string "Line to add: " add
)))
1367 (when (get-buffer-window bufname
)
1368 (delete-window (get-buffer-window bufname
)))
1370 ;; Make sure the info is not saved.
1371 (when (null auth-source-save-behavior
)
1374 (when (< 0 (length add
))
1379 (write-region (point-min) (point-max) file nil
'silent
)
1380 ;; Make the .authinfo file non-world-readable.
1381 (set-file-modes file
#o600
)
1382 (auth-source-do-debug
1383 "auth-source-netrc-create: wrote 1 new line to %s"
1385 (message "Saved new authentication information to %s" file
)
1387 (aput 'auth-source-netrc-cache key
"ran"))))
1389 ;;; Backend specific parsing: Secrets API backend
1391 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1392 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1393 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1394 ;;; (let ((auth-sources '(default))) (auth-source-search))
1395 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1396 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1398 (defun* auth-source-secrets-search
(&rest
1400 &key backend create delete label
1401 type max host user port
1403 "Search the Secrets API; spec is like `auth-source'.
1405 The :label key specifies the item's label. It is the only key
1406 that can specify a substring. Any :label value besides a string
1407 will allow any label.
1409 All other search keys must match exactly. If you need substring
1410 matching, do a wider search and narrow it down yourself.
1412 You'll get back all the properties of the token as a plist.
1414 Here's an example that looks for the first item in the 'Login'
1417 \(let ((auth-sources '(\"secrets:Login\")))
1418 (auth-source-search :max 1)
1420 Here's another that looks for the first item in the 'Login'
1421 Secrets collection whose label contains 'gnus':
1423 \(let ((auth-sources '(\"secrets:Login\")))
1424 (auth-source-search :max 1 :label \"gnus\")
1426 And this one looks for the first item in the 'Login' Secrets
1427 collection that's a Google Chrome entry for the git.gnus.org site
1428 authentication tokens:
1430 \(let ((auth-sources '(\"secrets:Login\")))
1431 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1435 (assert (not create
) nil
1436 "The Secrets API auth-source backend doesn't support creation yet")
1438 ;; (secrets-delete-item coll elt)
1439 (assert (not delete
) nil
1440 "The Secrets API auth-source backend doesn't support deletion yet")
1442 (let* ((coll (oref backend source
))
1443 (max (or max
5000)) ; sanity check: default to stop at 5K
1444 (ignored-keys '(:create
:delete
:max
:backend
:label
))
1445 (search-keys (loop for i below
(length spec
) by
2
1446 unless
(memq (nth i spec
) ignored-keys
)
1447 collect
(nth i spec
)))
1448 ;; build a search spec without the ignored keys
1449 ;; if a search key is nil or t (match anything), we skip it
1450 (search-spec (apply 'append
(mapcar
1452 (if (or (null (plist-get spec k
))
1453 (eq t
(plist-get spec k
)))
1455 (list k
(plist-get spec k
))))
1457 ;; needed keys (always including host, login, port, and secret)
1458 (returned-keys (mm-delete-duplicates (append
1459 '(:host
:login
:port
:secret
)
1461 (items (loop for item in
(apply 'secrets-search-items coll search-spec
)
1462 unless
(and (stringp label
)
1463 (not (string-match label item
)))
1465 ;; TODO: respect max in `secrets-search-items', not after the fact
1466 (items (butlast items
(- (length items
) max
)))
1467 ;; convert the item name to a full plist
1468 (items (mapcar (lambda (item)
1470 ;; make an entry for the secret (password) element
1473 (lexical-let ((v (secrets-get-secret coll item
)))
1475 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1477 (mapcar (lambda (entry)
1478 (list (car entry
) (cdr entry
)))
1479 (secrets-get-attributes coll item
)))))
1481 ;; ensure each item has each key in `returned-keys'
1482 (items (mapcar (lambda (plist)
1485 (mapcar (lambda (req)
1486 (if (plist-get plist req
)
1494 (defun* auth-source-secrets-create
(&rest
1496 &key backend type max host user port
1499 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1502 ;;; Backend specific parsing: PLSTORE backend
1504 (defun* auth-source-plstore-search
(&rest
1506 &key backend create delete label
1507 type max host user port
1509 "Search the PLSTORE; spec is like `auth-source'."
1510 (let* ((store (oref backend data
))
1511 (max (or max
5000)) ; sanity check: default to stop at 5K
1512 (ignored-keys '(:create
:delete
:max
:backend
:require
))
1513 (search-keys (loop for i below
(length spec
) by
2
1514 unless
(memq (nth i spec
) ignored-keys
)
1515 collect
(nth i spec
)))
1516 ;; build a search spec without the ignored keys
1517 ;; if a search key is nil or t (match anything), we skip it
1518 (search-spec (apply 'append
(mapcar
1520 (let ((v (plist-get spec k
)))
1528 ;; needed keys (always including host, login, port, and secret)
1529 (returned-keys (mm-delete-duplicates (append
1530 '(:host
:login
:port
:secret
)
1532 (items (plstore-find store search-spec
))
1533 (item-names (mapcar #'car items
))
1534 (items (butlast items
(- (length items
) max
)))
1535 ;; convert the item to a full plist
1536 (items (mapcar (lambda (item)
1537 (let* ((plist (copy-tree (cdr item
)))
1538 (secret (plist-member plist
:secret
)))
1542 (lexical-let ((v (car (cdr secret
))))
1546 ;; ensure each item has each key in `returned-keys'
1547 (items (mapcar (lambda (plist)
1550 (mapcar (lambda (req)
1551 (if (plist-get plist req
)
1558 ;; if we need to create an entry AND none were found to match
1562 ;; create based on the spec and record the value
1564 ;; if the user did not want to create the entry
1565 ;; in the file, it will be returned
1566 (apply (slot-value backend
'create-function
) spec
)
1567 ;; if not, we do the search again without :create
1568 ;; to get the updated data.
1570 ;; the result will be returned, even if the search fails
1571 (apply 'auth-source-plstore-search
1572 (plist-put spec
:create nil
)))))
1575 (dolist (item-name item-names
)
1576 (plstore-delete store item-name
))
1577 (plstore-save store
)))
1580 (defun* auth-source-plstore-create
(&rest spec
1582 secret host user port create
1584 (let* ((base-required '(host user port secret
))
1585 (base-secret '(secret))
1586 ;; we know (because of an assertion in auth-source-search) that the
1587 ;; :create parameter is either t or a list (which includes nil)
1588 (create-extra (if (eq t create
) nil create
))
1589 (current-data (car (auth-source-search :max
1
1592 (required (append base-required create-extra
))
1593 (file (oref backend source
))
1595 ;; `valist' is an alist
1597 ;; `artificial' will be returned if no creation is needed
1601 ;; only for base required elements (defined as function parameters):
1602 ;; fill in the valist with whatever data we may have from the search
1603 ;; we complete the first value if it's a list and use the value otherwise
1604 (dolist (br base-required
)
1605 (when (symbol-value br
)
1606 (let ((br-choice (cond
1607 ;; all-accepting choice (predicate is t)
1608 ((eq t
(symbol-value br
)) nil
)
1609 ;; just the value otherwise
1610 (t (symbol-value br
)))))
1612 (aput 'valist br br-choice
)))))
1614 ;; for extra required elements, see if the spec includes a value for them
1615 (dolist (er create-extra
)
1616 (let ((name (concat ":" (symbol-name er
)))
1617 (keys (loop for i below
(length spec
) by
2
1618 collect
(nth i spec
))))
1620 (when (equal (symbol-name k
) name
)
1621 (aput 'valist er
(plist-get spec k
))))))
1623 ;; for each required element
1624 (dolist (r required
)
1625 (let* ((data (aget valist r
))
1626 ;; take the first element if the data is a list
1627 (data (or (auth-source-netrc-element-or-first data
)
1628 (plist-get current-data
1629 (intern (format ":%s" r
) obarray
))))
1630 ;; this is the default to be offered
1631 (given-default (aget auth-source-creation-defaults r
))
1632 ;; the default supplementals are simple:
1633 ;; for the user, try `given-default' and then (user-login-name);
1634 ;; otherwise take `given-default'
1636 ((and (not given-default
) (eq r
'user
))
1639 (printable-defaults (list
1642 (auth-source-netrc-element-or-first
1643 (aget valist
'user
))
1644 (plist-get artificial
:user
)
1648 (auth-source-netrc-element-or-first
1649 (aget valist
'host
))
1650 (plist-get artificial
:host
)
1654 (auth-source-netrc-element-or-first
1655 (aget valist
'port
))
1656 (plist-get artificial
:port
)
1658 (prompt (or (aget auth-source-creation-prompts r
)
1660 (secret "%p password for %u@%h: ")
1661 (user "%p user name for %h: ")
1662 (host "%p host name for user %u: ")
1663 (port "%p port for %u@%h: "))
1664 (format "Enter %s (%%u@%%h:%%p): " r
)))
1665 (prompt (auth-source-format-prompt
1667 `((?u
,(aget printable-defaults
'user
))
1668 (?h
,(aget printable-defaults
'host
))
1669 (?p
,(aget printable-defaults
'port
))))))
1671 ;; Store the data, prompting for the password if needed.
1674 (or (eval default
) (read-passwd prompt
))
1675 (if (stringp default
)
1676 (read-string (if (string-match ": *\\'" prompt
)
1677 (concat (substring prompt
0 (match-beginning 0))
1678 " (default " default
"): ")
1679 (concat prompt
"(default " default
") "))
1684 (if (member r base-secret
)
1685 (setq secret-artificial
1686 (plist-put secret-artificial
1687 (intern (concat ":" (symbol-name r
)))
1689 (setq artificial
(plist-put artificial
1690 (intern (concat ":" (symbol-name r
)))
1692 (plstore-put (oref backend data
)
1693 (sha1 (format "%s@%s:%s"
1694 (plist-get artificial
:user
)
1695 (plist-get artificial
:host
)
1696 (plist-get artificial
:port
)))
1697 artificial secret-artificial
)
1698 (if (y-or-n-p (format "Save auth info to file %s? "
1699 (plstore-get-file (oref backend data
))))
1700 (plstore-save (oref backend data
)))))
1704 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1706 ;; deprecate the old interface
1707 (make-obsolete 'auth-source-user-or-password
1708 'auth-source-search
"Emacs 24.1")
1709 (make-obsolete 'auth-source-forget-user-or-password
1710 'auth-source-forget
"Emacs 24.1")
1712 (defun auth-source-user-or-password
1713 (mode host port
&optional username create-missing delete-existing
)
1714 "Find MODE (string or list of strings) matching HOST and PORT.
1716 DEPRECATED in favor of `auth-source-search'!
1718 USERNAME is optional and will be used as \"login\" in a search
1719 across the Secret Service API (see secrets.el) if the resulting
1720 items don't have a username. This means that if you search for
1721 username \"joe\" and it matches an item but the item doesn't have
1722 a :user attribute, the username \"joe\" will be returned.
1724 A non nil DELETE-EXISTING means deleting any matching password
1725 entry in the respective sources. This is useful only when
1726 CREATE-MISSING is non nil as well; the intended use case is to
1727 remove wrong password entries.
1729 If no matching entry is found, and CREATE-MISSING is non nil,
1730 the password will be retrieved interactively, and it will be
1731 stored in the password database which matches best (see
1734 MODE can be \"login\" or \"password\"."
1735 (auth-source-do-debug
1736 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1737 mode host port username
)
1739 (let* ((listy (listp mode
))
1740 (mode (if listy mode
(list mode
)))
1742 (format "%s %s:%s %s" mode host port username
)
1743 (format "%s %s:%s" mode host port
)))
1744 (search (list :host host
:port port
))
1745 (search (if username
(append search
(list :user username
)) search
))
1746 (search (if create-missing
1747 (append search
(list :create t
))
1749 (search (if delete-existing
1750 (append search
(list :delete t
))
1752 ;; (found (if (not delete-existing)
1753 ;; (gethash cname auth-source-cache)
1754 ;; (remhash cname auth-source-cache)
1759 (auth-source-do-debug
1760 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1762 ;; don't show the password
1763 (if (and (member "password" mode
) t
)
1767 found
) ; return the found data
1768 ;; else, if not found, search with a max of 1
1769 (let ((choice (nth 0 (apply 'auth-source-search
1770 (append '(:max
1) search
)))))
1774 ((equal "password" m
)
1775 (push (if (plist-get choice
:secret
)
1776 (funcall (plist-get choice
:secret
))
1779 (push (plist-get choice
:user
) found
)))))
1780 (setq found
(nreverse found
))
1781 (setq found
(if listy found
(car-safe found
)))))
1785 (defun auth-source-user-and-password (host &optional user
)
1786 (let* ((auth-info (car
1790 :user
"yourusername"
1792 :require
'(:user
:secret
)
1797 :require
'(:user
:secret
)
1799 (user (plist-get auth-info
:user
))
1800 (password (plist-get auth-info
:secret
)))
1801 (when (functionp password
)
1802 (setq password
(funcall password
)))
1803 (list user password auth-info
)))
1805 (provide 'auth-source
)
1807 ;;; auth-source.el ends here