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)
46 (eval-when-compile (require 'cl))
48 (or (ignore-errors (require 'eieio))
49 ;; gnus-fallback-lib/ from gnus/lisp/gnus-fallback-lib
51 (let ((load-path (cons (expand-file-name
52 "gnus-fallback-lib/eieio"
53 (file-name-directory (locate-library "gnus")))
57 "eieio not found in `load-path' or gnus-fallback-lib/ directory.")))
59 (autoload 'secrets-create-item "secrets")
60 (autoload 'secrets-delete-item "secrets")
61 (autoload 'secrets-get-alias "secrets")
62 (autoload 'secrets-get-attributes "secrets")
63 (autoload 'secrets-get-secret "secrets")
64 (autoload 'secrets-list-collections "secrets")
65 (autoload 'secrets-search-items "secrets")
67 (autoload 'rfc2104-hash "rfc2104")
69 (autoload 'plstore-open "plstore")
70 (autoload 'plstore-find "plstore")
71 (autoload 'plstore-put "plstore")
72 (autoload 'plstore-delete "plstore")
73 (autoload 'plstore-save "plstore")
74 (autoload 'plstore-get-file "plstore")
76 (autoload 'epg-make-context "epg")
77 (autoload 'epg-context-set-passphrase-callback "epg")
78 (autoload 'epg-decrypt-string "epg")
79 (autoload 'epg-context-set-armor "epg")
80 (autoload 'epg-encrypt-string "epg")
82 (autoload 'help-mode "help-mode" nil t)
84 (defvar secrets-enabled)
86 (defgroup auth-source nil
87 "Authentication sources."
88 :version "23.1" ;; No Gnus
92 (defcustom auth-source-cache-expiry 7200
93 "How many seconds passwords are cached, or nil to disable
94 expiring. Overrides `password-cache-expiry' through a
98 :type '(choice (const :tag "Never" nil)
99 (const :tag "All Day" 86400)
100 (const :tag "2 Hours" 7200)
101 (const :tag "30 Minutes" 1800)
102 (integer :tag "Seconds")))
104 ;;; The slots below correspond with the `auth-source-search' spec,
105 ;;; so a backend with :host set, for instance, would match only
106 ;;; searches for that host. Normally they are nil.
107 (defclass auth-source-backend ()
108 ((type :initarg :type
112 :documentation "The backend type.")
113 (source :initarg :source
116 :documentation "The backend source.")
121 :documentation "The backend host.")
126 :documentation "The backend user.")
131 :documentation "The backend protocol.")
134 :documentation "Internal backend data.")
135 (create-function :initarg :create-function
139 :documentation "The create function.")
140 (search-function :initarg :search-function
144 :documentation "The search function.")))
146 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
147 (pop3 "pop3" "pop" "pop3s" "110" "995")
151 "List of authentication protocols and their names"
154 :version "23.2" ;; No Gnus
155 :type '(repeat :tag "Authentication Protocols"
156 (cons :tag "Protocol Entry"
157 (symbol :tag "Protocol")
159 (string :tag "Name")))))
161 ;;; generate all the protocols in a format Customize can use
162 ;;; TODO: generate on the fly from auth-source-protocols
163 (defconst auth-source-protocols-customize
165 (let ((p (car-safe a)))
167 :tag (upcase (symbol-name p))
169 auth-source-protocols))
171 (defvar auth-source-creation-defaults nil
172 "Defaults for creating token values. Usually let-bound.")
174 (defvar auth-source-creation-prompts nil
175 "Default prompts for token values. Usually let-bound.")
177 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
179 (defcustom auth-source-save-behavior 'ask
180 "If set, auth-source will respect it for save behavior."
182 :version "23.2" ;; No Gnus
184 :tag "auth-source new token save behavior"
185 (const :tag "Always save" t)
186 (const :tag "Never save" nil)
187 (const :tag "Ask" ask)))
189 ;; 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)))
190 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
192 (defcustom auth-source-netrc-use-gpg-tokens 'never
193 "Set this to tell auth-source when to create GPG password
194 tokens in netrc files. It's either an alist or `never'.
195 Note that if EPA/EPG is not available, this should NOT be used."
197 :version "23.2" ;; No Gnus
199 (const :tag "Always use GPG password tokens" (t gpg))
200 (const :tag "Never use GPG password tokens" never)
201 (repeat :tag "Use a lookup list"
203 (choice :tag "Matcher"
204 (const :tag "Match anything" t)
205 (const :tag "The EPA encrypted file extensions"
206 ,(if (boundp 'epa-file-auto-mode-alist-entry)
208 'epa-file-auto-mode-alist-entry))
210 (regexp :tag "Regular expression"))
211 (choice :tag "What to do"
212 (const :tag "Save GPG-encrypted password tokens" gpg)
213 (const :tag "Don't encrypt tokens" never))))))
215 (defvar auth-source-magic "auth-source-magic ")
217 (defcustom auth-source-do-cache t
218 "Whether auth-source should cache information with `password-cache'."
220 :version "23.2" ;; No Gnus
223 (defcustom auth-source-debug nil
224 "Whether auth-source should log debug messages.
226 If the value is nil, debug messages are not logged.
228 If the value is t, debug messages are logged with `message'. In
229 that case, your authentication data will be in the clear (except
232 If the value is a function, debug messages are logged by calling
233 that function using the same arguments as `message'."
235 :version "23.2" ;; No Gnus
237 :tag "auth-source debugging mode"
238 (const :tag "Log using `message' to the *Messages* buffer" t)
239 (const :tag "Log all trivia with `message' to the *Messages* buffer"
241 (function :tag "Function that takes arguments like `message'")
242 (const :tag "Don't log anything" nil)))
244 (defcustom auth-sources '("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
245 "List of authentication sources.
247 The default will get login and password information from
248 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
249 packages to be encrypted. If that file doesn't exist, it will
250 try the unencrypted version \"~/.authinfo\" and the famous
253 See the auth.info manual for details.
255 Each entry is the authentication type with optional properties.
257 It's best to customize this with `M-x customize-variable' because the choices
258 can get pretty complex."
260 :version "24.1" ;; No Gnus
261 :type `(repeat :tag "Authentication Sources"
263 (string :tag "Just a file")
264 (const :tag "Default Secrets API Collection" 'default)
265 (const :tag "Login Secrets API Collection" "secrets:Login")
266 (const :tag "Temp Secrets API Collection" "secrets:session")
267 (list :tag "Source definition"
268 (const :format "" :value :source)
269 (choice :tag "Authentication backend choice"
270 (string :tag "Authentication Source (file)")
272 :tag "Secret Service API/KWallet/GNOME Keyring"
273 (const :format "" :value :secrets)
274 (choice :tag "Collection to use"
275 (string :tag "Collection name")
276 (const :tag "Default" 'default)
277 (const :tag "Login" "Login")
279 :tag "Temporary" "session"))))
280 (repeat :tag "Extra Parameters" :inline t
281 (choice :tag "Extra parameter"
284 (const :format "" :value :host)
285 (choice :tag "Host (machine) choice"
288 :tag "Regular expression")))
291 (const :format "" :value :port)
295 ,@auth-source-protocols-customize))
296 (list :tag "User" :inline t
297 (const :format "" :value :user)
299 :tag "Personality/Username"
304 (defcustom auth-source-gpg-encrypt-to t
305 "List of recipient keys that `authinfo.gpg' encrypted to.
306 If the value is not a list, symmetric encryption will be used."
308 :version "24.1" ;; No Gnus
309 :type '(choice (const :tag "Symmetric encryption" t)
310 (repeat :tag "Recipient public keys"
311 (string :tag "Recipient public key"))))
313 ;; temp for debugging
314 ;; (unintern 'auth-source-protocols)
315 ;; (unintern 'auth-sources)
316 ;; (customize-variable 'auth-sources)
317 ;; (setq auth-sources nil)
318 ;; (format "%S" auth-sources)
319 ;; (customize-variable 'auth-source-protocols)
320 ;; (setq auth-source-protocols nil)
321 ;; (format "%S" auth-source-protocols)
322 ;; (auth-source-pick nil :host "a" :port 'imap)
323 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
324 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
325 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
326 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
327 ;; (auth-source-protocol-defaults 'imap)
329 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
330 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
331 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
332 (defun auth-source-do-debug (&rest msg)
333 (when auth-source-debug
334 (apply 'auth-source-do-warn msg)))
336 (defun auth-source-do-trivia (&rest msg)
337 (when (or (eq auth-source-debug 'trivia)
338 (functionp auth-source-debug))
339 (apply 'auth-source-do-warn msg)))
341 (defun auth-source-do-warn (&rest msg)
343 ;; set logger to either the function in auth-source-debug or 'message
344 ;; note that it will be 'message if auth-source-debug is nil
345 (if (functionp auth-source-debug)
351 ;;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
352 (defun auth-source-read-char-choice (prompt choices)
353 "Read one of CHOICES by `read-char-choice', or `read-char'.
354 `dropdown-list' support is disabled because it doesn't work reliably.
355 Only one of CHOICES will be returned. The PROMPT is augmented
356 with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
358 (let* ((prompt-choices
359 (apply 'concat (loop for c in choices
360 collect (format "%c/" c))))
361 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
362 (full-prompt (concat prompt prompt-choices))
365 (while (not (memq k choices))
367 ((fboundp 'read-char-choice)
368 (read-char-choice full-prompt choices))
369 (t (message "%s" full-prompt)
370 (setq k (read-char))))))
373 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
374 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
375 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
376 ;; (:source (:secrets "session") :host t :port t :user "joe")
377 ;; (:source (:secrets "Login") :host t :port t)
378 ;; (:source "~/.authinfo.gpg" :host t :port t)))
380 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
381 ;; (:source (:secrets "session") :host t :port t :user "joe")
382 ;; (:source (:secrets "Login") :host t :port t)
385 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
387 ;; (auth-source-backend-parse "myfile.gpg")
388 ;; (auth-source-backend-parse 'default)
389 ;; (auth-source-backend-parse "secrets:Login")
391 (defun auth-source-backend-parse (entry)
392 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
393 (auth-source-backend-parse-parameters
396 ;; take 'default and recurse to get it as a Secrets API default collection
397 ;; matching any user, host, and protocol
399 (auth-source-backend-parse '(:source (:secrets default))))
400 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
401 ;; matching any user, host, and protocol
402 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
403 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
404 ;; take just a file name and recurse to get it as a netrc file
405 ;; matching any user, host, and protocol
407 (auth-source-backend-parse `(:source ,entry)))
409 ;; a file name with parameters
410 ((stringp (plist-get entry :source))
411 (if (equal (file-name-extension (plist-get entry :source)) "plist")
413 (plist-get entry :source)
414 :source (plist-get entry :source)
416 :search-function 'auth-source-plstore-search
417 :create-function 'auth-source-plstore-create
418 :data (plstore-open (plist-get entry :source)))
420 (plist-get entry :source)
421 :source (plist-get entry :source)
423 :search-function 'auth-source-netrc-search
424 :create-function 'auth-source-netrc-create)))
426 ;; the Secrets API. We require the package, in order to have a
427 ;; defined value for `secrets-enabled'.
429 (not (null (plist-get entry :source))) ; the source must not be nil
430 (listp (plist-get entry :source)) ; and it must be a list
431 (require 'secrets nil t) ; and we must load the Secrets API
432 secrets-enabled) ; and that API must be enabled
434 ;; the source is either the :secrets key in ENTRY or
435 ;; if that's missing or nil, it's "session"
436 (let ((source (or (plist-get (plist-get entry :source) :secrets)
439 ;; if the source is a symbol, we look for the alias named so,
440 ;; and if that alias is missing, we use "Login"
441 (when (symbolp source)
442 (setq source (or (secrets-get-alias (symbol-name source))
445 (if (featurep 'secrets)
447 (format "Secrets API (%s)" source)
450 :search-function 'auth-source-secrets-search
451 :create-function 'auth-source-secrets-create)
453 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
455 (format "Ignored Secrets API (%s)" source)
462 "auth-source-backend-parse: invalid backend spec: %S" entry)
468 (defun auth-source-backend-parse-parameters (entry backend)
469 "Fills in the extra auth-source-backend parameters of ENTRY.
470 Using the plist ENTRY, get the :host, :port, and :user search
472 (let ((entry (if (stringp entry)
476 (when (setq val (plist-get entry :host))
477 (oset backend host val))
478 (when (setq val (plist-get entry :user))
479 (oset backend user val))
480 (when (setq val (plist-get entry :port))
481 (oset backend port val)))
484 ;; (mapcar 'auth-source-backend-parse auth-sources)
486 (defun* auth-source-search (&rest spec
487 &key type max host user port secret
488 require create delete
490 "Search or modify authentication backends according to SPEC.
492 This function parses `auth-sources' for matches of the SPEC
493 plist. It can optionally create or update an authentication
494 token if requested. A token is just a standard Emacs property
495 list with a :secret property that can be a function; all the
496 other properties will always hold scalar values.
498 Typically the :secret property, if present, contains a password.
500 Common search keys are :max, :host, :port, and :user. In
501 addition, :create specifies how tokens will be or created.
502 Finally, :type can specify which backend types you want to check.
504 A string value is always matched literally. A symbol is matched
505 as its string value, literally. All the SPEC values can be
506 single values (symbol or string) or lists thereof (in which case
507 any of the search terms matches).
509 :create t means to create a token if possible.
511 A new token will be created if no matching tokens were found.
512 The new token will have only the keys the backend requires. For
513 the netrc backend, for instance, that's the user, host, and
518 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
519 (A . \"default A\"))))
520 (auth-source-search :host \"mine\" :type 'netrc :max 1
521 :P \"pppp\" :Q \"qqqq\"
526 \"Search for any entry matching host 'mine' in backends of type
527 'netrc', maximum one result.
529 Create a new entry if you found none. The netrc backend will
530 automatically require host, user, and port. The host will be
531 'mine'. We prompt for the user with default 'defaultUser' and
532 for the port without a default. We will not prompt for A, Q,
533 or P. The resulting token will only have keys user, host, and
536 :create '(A B C) also means to create a token if possible.
538 The behavior is like :create t but if the list contains any
539 parameter, that parameter will be required in the resulting
540 token. The value for that parameter will be obtained from the
541 search parameters or from user input. If any queries are needed,
542 the alist `auth-source-creation-defaults' will be checked for the
543 default value. If the user, host, or port are missing, the alist
544 `auth-source-creation-prompts' will be used to look up the
545 prompts IN THAT ORDER (so the 'user prompt will be queried first,
546 then 'host, then 'port, and finally 'secret). Each prompt string
547 can use %u, %h, and %p to show the user, host, and port.
551 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
552 (A . \"default A\")))
553 (auth-source-creation-prompts
554 '((password . \"Enter IMAP password for %h:%p: \"))))
555 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
556 :P \"pppp\" :Q \"qqqq\"
561 \"Search for any entry matching host 'nonesuch'
562 or 'twosuch' in backends of type 'netrc', maximum one result.
564 Create a new entry if you found none. The netrc backend will
565 automatically require host, user, and port. The host will be
566 'nonesuch' and Q will be 'qqqq'. We prompt for the password
567 with the shown prompt. We will not prompt for Q. The resulting
568 token will have keys user, host, port, A, B, and Q. It will not
569 have P with any value, even though P is used in the search to
570 find only entries that have P set to 'pppp'.\"
572 When multiple values are specified in the search parameter, the
573 user is prompted for which one. So :host (X Y Z) would ask the
574 user to choose between X, Y, and Z.
576 This creation can fail if the search was not specific enough to
577 create a new token (it's up to the backend to decide that). You
578 should `catch' the backend-specific error as usual. Some
579 backends (netrc, at least) will prompt the user rather than throw
582 :require (A B C) means that only results that contain those
583 tokens will be returned. Thus for instance requiring :secret
584 will ensure that any results will actually have a :secret
587 :delete t means to delete any found entries. nil by default.
588 Use `auth-source-delete' in ELisp code instead of calling
589 `auth-source-search' directly with this parameter.
591 :type (X Y Z) will check only those backend types. 'netrc and
592 'secrets are the only ones supported right now.
594 :max N means to try to return at most N items (defaults to 1).
595 When 0 the function will return just t or nil to indicate if any
596 matches were found. More than N items may be returned, depending
597 on the search and the backend.
599 :host (X Y Z) means to match only hosts X, Y, or Z according to
600 the match rules above. Defaults to t.
602 :user (X Y Z) means to match only users X, Y, or Z according to
603 the match rules above. Defaults to t.
605 :port (P Q R) means to match only protocols P, Q, or R.
608 :K (V1 V2 V3) for any other key K will match values V1, V2, or
609 V3 (note the match rules above).
611 The return value is a list with at most :max tokens. Each token
612 is a plist with keys :backend :host :port :user, plus any other
613 keys provided by the backend (notably :secret). But note the
614 exception for :max 0, which see above.
616 The token can hold a :save-function key. If you call that, the
617 user will be prompted to save the data to the backend. You can't
618 request that this should happen right after creation, because
619 `auth-source-search' has no way of knowing if the token is
620 actually useful. So the caller must arrange to call this function.
622 The token's :secret key can hold a function. In that case you
623 must call it to obtain the actual value."
624 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
626 (ignored-keys '(:require :create :delete :max))
627 (keys (loop for i below (length spec) by 2
628 unless (memq (nth i spec) ignored-keys)
629 collect (nth i spec)))
630 (cached (auth-source-remembered-p spec))
631 ;; note that we may have cached results but found is still nil
632 ;; (there were no results from the search)
633 (found (auth-source-recall spec))
634 filtered-backends accessor-key backend)
636 (if (and cached auth-source-do-cache)
637 (auth-source-do-debug
638 "auth-source-search: found %d CACHED results matching %S"
642 (or (eq t create) (listp create)) t
643 "Invalid auth-source :create parameter (must be t or a list): %s %s")
647 "Invalid auth-source :require parameter (must be a list): %s")
649 (setq filtered-backends (copy-sequence backends))
650 (dolist (backend backends)
652 ;; ignore invalid slots
653 (condition-case signal
654 (unless (eval `(auth-source-search-collection
656 (oref backend ,key)))
657 (setq filtered-backends (delq backend filtered-backends))
659 (invalid-slot-name))))
661 (auth-source-do-trivia
662 "auth-source-search: found %d backends matching %S"
663 (length filtered-backends) spec)
665 ;; (debug spec "filtered" filtered-backends)
666 ;; First go through all the backends without :create, so we can
668 (setq found (auth-source-search-backends filtered-backends
672 ;; create is always nil here
676 (auth-source-do-debug
677 "auth-source-search: found %d results (max %d) matching %S"
678 (length found) max spec)
680 ;; If we didn't find anything, then we allow the backend(s) to
681 ;; create the entries.
684 (setq found (auth-source-search-backends filtered-backends
690 (auth-source-do-debug
691 "auth-source-search: CREATED %d results (max %d) matching %S"
692 (length found) max spec))
694 ;; note we remember the lack of result too, if it's applicable
695 (when auth-source-do-cache
696 (auth-source-remember spec found)))
700 (defun auth-source-search-backends (backends spec max create delete require)
702 (dolist (backend backends)
703 (when (> max (length matches)) ; when we need more matches...
704 (let* ((bmatches (apply
705 (slot-value backend 'search-function)
707 ;; note we're overriding whatever the spec
708 ;; has for :require, :create, and :delete
714 (auth-source-do-trivia
715 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
716 (length bmatches) max
717 (slot-value backend :type)
718 (slot-value backend :source)
720 (setq matches (append matches bmatches))))))
723 ;;; (auth-source-search :max 1)
724 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
725 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
726 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
728 (defun* auth-source-delete (&rest spec
731 "Delete entries from the authentication backends according to SPEC.
732 Calls `auth-source-search' with the :delete property in SPEC set to t.
733 The backend may not actually delete the entries.
735 Returns the deleted entries."
736 (auth-source-search (plist-put spec :delete t)))
738 (defun auth-source-search-collection (collection value)
739 "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
740 (when (and (atom collection) (not (eq t collection)))
741 (setq collection (list collection)))
743 ;; (debug :collection collection :value value)
744 (or (eq collection t)
746 (equal collection value)
747 (member value collection)))
749 (defvar auth-source-netrc-cache nil)
751 (defun auth-source-forget-all-cached ()
752 "Forget all cached auth-source data."
754 (loop for sym being the symbols of password-data
755 ;; when the symbol name starts with auth-source-magic
756 when (string-match (concat "^" auth-source-magic)
759 do (password-cache-remove (symbol-name sym)))
760 (setq auth-source-netrc-cache nil))
762 (defun auth-source-format-cache-entry (spec)
763 "Format SPEC entry to put it in the password cache."
764 (concat auth-source-magic (format "%S" spec)))
766 (defun auth-source-remember (spec found)
767 "Remember FOUND search results for SPEC."
768 (let ((password-cache-expiry auth-source-cache-expiry))
770 (auth-source-format-cache-entry spec) found)))
772 (defun auth-source-recall (spec)
773 "Recall FOUND search results for SPEC."
774 (password-read-from-cache (auth-source-format-cache-entry spec)))
776 (defun auth-source-remembered-p (spec)
777 "Check if SPEC is remembered."
779 (auth-source-format-cache-entry spec)))
781 (defun auth-source-forget (spec)
782 "Forget any cached data matching SPEC exactly.
784 This is the same SPEC you passed to `auth-source-search'.
785 Returns t or nil for forgotten or not found."
786 (password-cache-remove (auth-source-format-cache-entry spec)))
788 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
790 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
791 ;;; (auth-source-remembered-p '(:host "wedd"))
792 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
793 ;;; (auth-source-remembered-p '(:host "xedd"))
794 ;;; (auth-source-remembered-p '(:host "zedd"))
795 ;;; (auth-source-recall '(:host "xedd"))
796 ;;; (auth-source-recall '(:host t))
797 ;;; (auth-source-forget+ :host t)
799 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
800 "Forget any cached data matching SPEC. Returns forgotten count.
802 This is not a full `auth-source-search' spec but works similarly.
803 For instance, \(:host \"myhost\" \"yourhost\") would find all the
804 cached data that was found with a search for those two hosts,
805 while \(:host t) would find all host entries."
808 (loop for sym being the symbols of password-data
809 ;; when the symbol name matches with auth-source-magic
810 when (and (setq sname (symbol-name sym))
811 (string-match (concat "^" auth-source-magic "\\(.+\\)")
813 ;; and the spec matches what was stored in the cache
814 (auth-source-specmatchp spec (read (match-string 1 sname))))
817 (password-cache-remove sname)
821 (defun auth-source-specmatchp (spec stored)
822 (let ((keys (loop for i below (length spec) by 2
823 collect (nth i spec))))
826 (unless (auth-source-search-collection (plist-get stored key)
827 (plist-get spec key))
831 ;;; (auth-source-pick-first-password :host "z.lifelogs.com")
832 ;;; (auth-source-pick-first-password :port "imap")
833 (defun auth-source-pick-first-password (&rest spec)
834 "Pick the first secret found from applying SPEC to `auth-source-search'."
835 (let* ((result (nth 0 (apply 'auth-source-search (plist-put spec :max 1))))
836 (secret (plist-get result :secret)))
838 (if (functionp secret)
842 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
843 (defun auth-source-format-prompt (prompt alist)
844 "Format PROMPT using %x (for any character x) specifiers in ALIST."
846 (let ((c (nth 0 cell))
849 (setq prompt (replace-regexp-in-string (format "%%%c" c)
854 (defun auth-source-ensure-strings (values)
855 (unless (listp values)
856 (setq values (list values)))
857 (mapcar (lambda (value)
863 ;;; Backend specific parsing: netrc/authinfo backend
865 (defun auth-source--aput-1 (alist key val)
868 (while (and (consp rest) (not (equal key (caar rest))))
869 (push (pop rest) seen))
871 (if (null rest) alist
872 (nconc (nreverse seen)
873 (if (equal key (caar rest)) (cdr rest) rest))))))
874 (defmacro auth-source--aput (var key val)
875 `(setq ,var (auth-source--aput-1 ,var ,key ,val)))
877 (defun auth-source--aget (alist key)
878 (cdr (assoc key alist)))
880 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
881 (defun* auth-source-netrc-parse (&rest
883 &key file max host user port delete require
885 "Parse FILE and return a list of all entries in the file.
886 Note that the MAX parameter is used so we can exit the parse early."
888 ;; We got already parsed contents; just return it.
890 (when (file-exists-p file)
891 (setq port (auth-source-ensure-strings port))
893 (let* ((tokens '("machine" "host" "default" "login" "user"
894 "password" "account" "macdef" "force"
896 (max (or max 5000)) ; sanity check: default to stop at 5K
898 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
899 (cached-mtime (plist-get cached :mtime))
900 (cached-secrets (plist-get cached :secret))
901 alist elem result pair)
903 (if (and (functionp cached-secrets)
905 (nth 5 (file-attributes file))))
907 (auth-source-do-trivia
908 "auth-source-netrc-parse: using CACHED file data for %s"
910 (insert (funcall cached-secrets)))
911 (insert-file-contents file)
912 ;; cache all netrc files (used to be just .gpg files)
913 ;; Store the contents of the file heavily encrypted in memory.
914 ;; (note for the irony-impaired: they are just obfuscated)
916 auth-source-netrc-cache file
917 (list :mtime (nth 5 (file-attributes file))
918 :secret (lexical-let ((v (mapcar '1+ (buffer-string))))
919 (lambda () (apply 'string (mapcar '1- v)))))))
920 (goto-char (point-min))
921 ;; Go through the file, line by line.
922 (while (and (not (eobp))
925 (narrow-to-region (point) (point-at-eol))
926 ;; For each line, get the tokens and values.
928 (skip-chars-forward "\t ")
929 ;; Skip lines that begin with a "#".
930 (if (eq (char-after) ?#)
931 (goto-char (point-max))
934 (if (= (following-char) ?\")
935 (read (current-buffer))
937 (point) (progn (skip-chars-forward "^\t ")
940 ((equal elem "macdef")
941 ;; We skip past the macro definition.
943 (while (and (zerop (forward-line 1))
945 (narrow-to-region (point) (point)))
946 ((member elem tokens)
947 ;; Tokens that don't have a following value are ignored,
949 (when (and pair (or (cdr pair)
950 (equal (car pair) "default")))
952 (setq pair (list elem)))
954 ;; Values that haven't got a preceding token are ignored.
958 (setq pair nil)))))))
962 (auth-source-search-collection
965 (auth-source--aget alist "machine")
966 (auth-source--aget alist "host")
968 (auth-source-search-collection
971 (auth-source--aget alist "login")
972 (auth-source--aget alist "account")
973 (auth-source--aget alist "user")
975 (auth-source-search-collection
978 (auth-source--aget alist "port")
979 (auth-source--aget alist "protocol")
982 ;; the required list of keys is nil, or
984 ;; every element of require is in the normalized list
985 (let ((normalized (nth 0 (auth-source-netrc-normalize
986 (list alist) file))))
987 (loop for req in require
988 always (plist-get normalized req)))))
990 (push (nreverse alist) result)
991 ;; to delete a line, we just comment it out
993 (goto-char (point-min))
1001 (when (< 0 modified)
1002 (when auth-source-gpg-encrypt-to
1003 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1004 ;; this buffer lets epa-file skip the key selection query
1005 ;; (see the `local-variable-p' check in
1006 ;; `epa-file-write-region').
1007 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1008 (make-local-variable 'epa-file-encrypt-to))
1009 (if (listp auth-source-gpg-encrypt-to)
1010 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1012 ;; ask AFTER we've successfully opened the file
1013 (when (y-or-n-p (format "Save file %s? (%d deletions)"
1015 (write-region (point-min) (point-max) file nil 'silent)
1016 (auth-source-do-debug
1017 "auth-source-netrc-parse: modified %d lines in %s"
1020 (nreverse result))))))
1022 (defvar auth-source-passphrase-alist nil)
1024 (defun auth-source-token-passphrase-callback-function (context key-id file)
1025 (let* ((file (file-truename file))
1026 (entry (assoc file auth-source-passphrase-alist))
1028 ;; return the saved passphrase, calling a function if needed
1029 (or (copy-sequence (if (functionp (cdr entry))
1030 (funcall (cdr entry))
1034 (setq entry (list file))
1035 (push entry auth-source-passphrase-alist))
1038 (format "Passphrase for %s tokens: " file)
1040 (setcdr entry (lexical-let ((p (copy-sequence passphrase)))
1044 ;; (auth-source-epa-extract-gpg-token "gpg:LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tClZlcnNpb246IEdudVBHIHYxLjQuMTEgKEdOVS9MaW51eCkKCmpBMEVBd01DT25qMjB1ak9rZnRneVI3K21iNm9aZWhuLzRad3cySkdlbnVaKzRpeEswWDY5di9icDI1U1dsQT0KPS9yc2wKLS0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo=" "~/.netrc")
1045 (defun auth-source-epa-extract-gpg-token (secret file)
1046 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1047 FILE is the file from which we obtained this token."
1048 (when (string-match "^gpg:\\(.+\\)" secret)
1049 (setq secret (base64-decode-string (match-string 1 secret))))
1050 (let ((context (epg-make-context 'OpenPGP))
1052 (epg-context-set-passphrase-callback
1054 (cons #'auth-source-token-passphrase-callback-function
1056 (epg-decrypt-string context secret)))
1058 ;; (insert (auth-source-epa-make-gpg-token "mysecret" "~/.netrc"))
1059 (defun auth-source-epa-make-gpg-token (secret file)
1060 (let ((context (epg-make-context 'OpenPGP))
1061 (pp-escape-newlines nil)
1063 (epg-context-set-armor context t)
1064 (epg-context-set-passphrase-callback
1066 (cons #'auth-source-token-passphrase-callback-function
1068 (setq cipher (epg-encrypt-string context secret nil))
1071 (base64-encode-region (point-min) (point-max) t)
1072 (concat "gpg:" (buffer-substring-no-properties
1076 (defun auth-source-netrc-normalize (alist filename)
1077 (mapcar (lambda (entry)
1079 (while (setq item (pop entry))
1080 (let ((k (car item))
1083 ;; apply key aliases
1084 (setq k (cond ((member k '("machine")) "host")
1085 ((member k '("login" "account")) "user")
1086 ((member k '("protocol")) "port")
1087 ((member k '("password")) "secret")
1090 ;; send back the secret in a function (lexical binding)
1091 (when (equal k "secret")
1092 (setq v (lexical-let ((lexv v)
1093 (token-decoder nil))
1094 (when (string-match "^gpg:" lexv)
1095 ;; it's a GPG token: create a token decoder
1096 ;; which unsets itself once
1100 (auth-source-epa-extract-gpg-token
1103 (setq token-decoder nil)))))
1106 (setq lexv (funcall token-decoder lexv)))
1108 (setq ret (plist-put ret
1109 (intern (concat ":" k))
1114 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
1115 ;;; (funcall secret)
1117 (defun* auth-source-netrc-search (&rest
1119 &key backend require create delete
1120 type max host user port
1122 "Given a property list SPEC, return search matches from the :backend.
1123 See `auth-source-search' for details on SPEC."
1124 ;; just in case, check that the type is correct (null or same as the backend)
1125 (assert (or (null type) (eq type (oref backend type)))
1126 t "Invalid netrc search: %s %s")
1128 (let ((results (auth-source-netrc-normalize
1129 (auth-source-netrc-parse
1133 :file (oref backend source)
1137 (oref backend source))))
1139 ;; if we need to create an entry AND none were found to match
1143 ;; create based on the spec and record the value
1145 ;; if the user did not want to create the entry
1146 ;; in the file, it will be returned
1147 (apply (slot-value backend 'create-function) spec)
1148 ;; if not, we do the search again without :create
1149 ;; to get the updated data.
1151 ;; the result will be returned, even if the search fails
1152 (apply 'auth-source-netrc-search
1153 (plist-put spec :create nil)))))
1156 (defun auth-source-netrc-element-or-first (v)
1161 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1162 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1164 (defun* auth-source-netrc-create (&rest spec
1166 secret host user port create
1168 (let* ((base-required '(host user port secret))
1169 ;; we know (because of an assertion in auth-source-search) that the
1170 ;; :create parameter is either t or a list (which includes nil)
1171 (create-extra (if (eq t create) nil create))
1172 (current-data (car (auth-source-search :max 1
1175 (required (append base-required create-extra))
1176 (file (oref backend source))
1178 ;; `valist' is an alist
1180 ;; `artificial' will be returned if no creation is needed
1183 ;; only for base required elements (defined as function parameters):
1184 ;; fill in the valist with whatever data we may have from the search
1185 ;; we complete the first value if it's a list and use the value otherwise
1186 (dolist (br base-required)
1187 (when (symbol-value br)
1188 (let ((br-choice (cond
1189 ;; all-accepting choice (predicate is t)
1190 ((eq t (symbol-value br)) nil)
1191 ;; just the value otherwise
1192 (t (symbol-value br)))))
1194 (auth-source--aput valist br br-choice)))))
1196 ;; for extra required elements, see if the spec includes a value for them
1197 (dolist (er create-extra)
1198 (let ((name (concat ":" (symbol-name er)))
1199 (keys (loop for i below (length spec) by 2
1200 collect (nth i spec))))
1202 (when (equal (symbol-name k) name)
1203 (auth-source--aput valist er (plist-get spec k))))))
1205 ;; for each required element
1206 (dolist (r required)
1207 (let* ((data (auth-source--aget valist r))
1208 ;; take the first element if the data is a list
1209 (data (or (auth-source-netrc-element-or-first data)
1210 (plist-get current-data
1211 (intern (format ":%s" r) obarray))))
1212 ;; this is the default to be offered
1213 (given-default (auth-source--aget
1214 auth-source-creation-defaults r))
1215 ;; the default supplementals are simple:
1216 ;; for the user, try `given-default' and then (user-login-name);
1217 ;; otherwise take `given-default'
1219 ((and (not given-default) (eq r 'user))
1222 (printable-defaults (list
1225 (auth-source-netrc-element-or-first
1226 (auth-source--aget valist 'user))
1227 (plist-get artificial :user)
1231 (auth-source-netrc-element-or-first
1232 (auth-source--aget valist 'host))
1233 (plist-get artificial :host)
1237 (auth-source-netrc-element-or-first
1238 (auth-source--aget valist 'port))
1239 (plist-get artificial :port)
1241 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1243 (secret "%p password for %u@%h: ")
1244 (user "%p user name for %h: ")
1245 (host "%p host name for user %u: ")
1246 (port "%p port for %u@%h: "))
1247 (format "Enter %s (%%u@%%h:%%p): " r)))
1248 (prompt (auth-source-format-prompt
1250 `((?u ,(auth-source--aget printable-defaults 'user))
1251 (?h ,(auth-source--aget printable-defaults 'host))
1252 (?p ,(auth-source--aget printable-defaults 'port))))))
1254 ;; Store the data, prompting for the password if needed.
1257 ;; Special case prompt for passwords.
1258 ;; 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)))
1259 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1260 (let* ((ep (format "Use GPG password tokens in %s?" file))
1263 ((eq auth-source-netrc-use-gpg-tokens 'never)
1265 ((listp auth-source-netrc-use-gpg-tokens)
1266 (let ((check (copy-sequence
1267 auth-source-netrc-use-gpg-tokens))
1270 (setq item (pop check))
1271 (when (or (eq (car item) t)
1272 (string-match (car item) file))
1273 (setq ret (cdr item))
1274 (setq check nil)))))
1276 (plain (or (eval default) (read-passwd prompt))))
1277 ;; ask if we don't know what to do (in which case
1278 ;; auth-source-netrc-use-gpg-tokens must be a list)
1280 (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1281 ;; TODO: save the defcustom now? or ask?
1282 (setq auth-source-netrc-use-gpg-tokens
1283 (cons `(,file ,gpg-encrypt)
1284 auth-source-netrc-use-gpg-tokens)))
1285 (if (eq gpg-encrypt 'gpg)
1286 (auth-source-epa-make-gpg-token plain file)
1288 (if (stringp default)
1289 (read-string (if (string-match ": *\\'" prompt)
1290 (concat (substring prompt 0 (match-beginning 0))
1291 " (default " default "): ")
1292 (concat prompt "(default " default ") "))
1297 (setq artificial (plist-put artificial
1298 (intern (concat ":" (symbol-name r)))
1300 (lexical-let ((data data))
1304 ;; When r is not an empty string...
1305 (when (and (stringp data)
1306 (< 0 (length data)))
1307 ;; this function is not strictly necessary but I think it
1308 ;; makes the code clearer -tzz
1309 (let ((printer (lambda ()
1310 ;; append the key (the symbol name of r)
1311 ;; and the value in r
1314 (if (zerop (length add)) "" " ")
1315 ;; remap auth-source tokens to netrc
1320 (port "port") ; redundant but clearer
1321 (t (symbol-name r)))
1322 (if (string-match "[\"# ]" data)
1325 (setq add (concat add (funcall printer)))))))
1330 (lexical-let ((file file)
1332 (lambda () (auth-source-netrc-saver file add))))
1336 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1337 (defun auth-source-netrc-saver (file add)
1338 "Save a line ADD in FILE, prompting along the way.
1339 Respects `auth-source-save-behavior'. Uses
1340 `auth-source-netrc-cache' to avoid prompting more than once."
1341 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1342 (cached (assoc key auth-source-netrc-cache)))
1345 (auth-source-do-trivia
1346 "auth-source-netrc-saver: found previous run for key %s, returning"
1349 (when (file-exists-p file)
1350 (insert-file-contents file))
1351 (when auth-source-gpg-encrypt-to
1352 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1353 ;; this buffer lets epa-file skip the key selection query
1354 ;; (see the `local-variable-p' check in
1355 ;; `epa-file-write-region').
1356 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1357 (make-local-variable 'epa-file-encrypt-to))
1358 (if (listp auth-source-gpg-encrypt-to)
1359 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1360 ;; we want the new data to be found first, so insert at beginning
1361 (goto-char (point-min))
1363 ;; Ask AFTER we've successfully opened the file.
1364 (let ((prompt (format "Save auth info to file %s? " file))
1365 (done (not (eq auth-source-save-behavior 'ask)))
1366 (bufname "*auth-source Help*")
1369 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1373 (with-output-to-temp-buffer bufname
1375 (concat "(y)es, save\n"
1376 "(n)o but use the info\n"
1377 "(N)o and don't ask to save again\n"
1379 "(?) for help as you can see.\n"))
1380 ;; Why? Doesn't with-output-to-temp-buffer already do
1381 ;; the exact same thing anyway? --Stef
1382 (set-buffer standard-output)
1389 (customize-save-variable 'auth-source-save-behavior nil))
1390 (?e (setq add (read-string "Line to add: " add)))
1393 (when (get-buffer-window bufname)
1394 (delete-window (get-buffer-window bufname)))
1396 ;; Make sure the info is not saved.
1397 (when (null auth-source-save-behavior)
1400 (when (< 0 (length add))
1405 (write-region (point-min) (point-max) file nil 'silent)
1406 ;; Make the .authinfo file non-world-readable.
1407 (set-file-modes file #o600)
1408 (auth-source-do-debug
1409 "auth-source-netrc-create: wrote 1 new line to %s"
1411 (message "Saved new authentication information to %s" file)
1413 (auth-source--aput auth-source-netrc-cache key "ran"))))
1415 ;;; Backend specific parsing: Secrets API backend
1417 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1418 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1419 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1420 ;;; (let ((auth-sources '(default))) (auth-source-search))
1421 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1422 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1424 (defun* auth-source-secrets-search (&rest
1426 &key backend create delete label
1427 type max host user port
1429 "Search the Secrets API; spec is like `auth-source'.
1431 The :label key specifies the item's label. It is the only key
1432 that can specify a substring. Any :label value besides a string
1433 will allow any label.
1435 All other search keys must match exactly. If you need substring
1436 matching, do a wider search and narrow it down yourself.
1438 You'll get back all the properties of the token as a plist.
1440 Here's an example that looks for the first item in the 'Login'
1443 \(let ((auth-sources '(\"secrets:Login\")))
1444 (auth-source-search :max 1)
1446 Here's another that looks for the first item in the 'Login'
1447 Secrets collection whose label contains 'gnus':
1449 \(let ((auth-sources '(\"secrets:Login\")))
1450 (auth-source-search :max 1 :label \"gnus\")
1452 And this one looks for the first item in the 'Login' Secrets
1453 collection that's a Google Chrome entry for the git.gnus.org site
1454 authentication tokens:
1456 \(let ((auth-sources '(\"secrets:Login\")))
1457 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1461 (assert (not create) nil
1462 "The Secrets API auth-source backend doesn't support creation yet")
1464 ;; (secrets-delete-item coll elt)
1465 (assert (not delete) nil
1466 "The Secrets API auth-source backend doesn't support deletion yet")
1468 (let* ((coll (oref backend source))
1469 (max (or max 5000)) ; sanity check: default to stop at 5K
1470 (ignored-keys '(:create :delete :max :backend :label))
1471 (search-keys (loop for i below (length spec) by 2
1472 unless (memq (nth i spec) ignored-keys)
1473 collect (nth i spec)))
1474 ;; build a search spec without the ignored keys
1475 ;; if a search key is nil or t (match anything), we skip it
1476 (search-spec (apply 'append (mapcar
1478 (if (or (null (plist-get spec k))
1479 (eq t (plist-get spec k)))
1481 (list k (plist-get spec k))))
1483 ;; needed keys (always including host, login, port, and secret)
1484 (returned-keys (mm-delete-duplicates (append
1485 '(:host :login :port :secret)
1487 (items (loop for item in (apply 'secrets-search-items coll search-spec)
1488 unless (and (stringp label)
1489 (not (string-match label item)))
1491 ;; TODO: respect max in `secrets-search-items', not after the fact
1492 (items (butlast items (- (length items) max)))
1493 ;; convert the item name to a full plist
1494 (items (mapcar (lambda (item)
1496 ;; make an entry for the secret (password) element
1499 (lexical-let ((v (secrets-get-secret coll item)))
1501 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1503 (mapcar (lambda (entry)
1504 (list (car entry) (cdr entry)))
1505 (secrets-get-attributes coll item)))))
1507 ;; ensure each item has each key in `returned-keys'
1508 (items (mapcar (lambda (plist)
1511 (mapcar (lambda (req)
1512 (if (plist-get plist req)
1520 (defun* auth-source-secrets-create (&rest
1522 &key backend type max host user port
1525 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1528 ;;; Backend specific parsing: PLSTORE backend
1530 (defun* auth-source-plstore-search (&rest
1532 &key backend create delete label
1533 type max host user port
1535 "Search the PLSTORE; spec is like `auth-source'."
1536 (let* ((store (oref backend data))
1537 (max (or max 5000)) ; sanity check: default to stop at 5K
1538 (ignored-keys '(:create :delete :max :backend :require))
1539 (search-keys (loop for i below (length spec) by 2
1540 unless (memq (nth i spec) ignored-keys)
1541 collect (nth i spec)))
1542 ;; build a search spec without the ignored keys
1543 ;; if a search key is nil or t (match anything), we skip it
1544 (search-spec (apply 'append (mapcar
1546 (let ((v (plist-get spec k)))
1554 ;; needed keys (always including host, login, port, and secret)
1555 (returned-keys (mm-delete-duplicates (append
1556 '(:host :login :port :secret)
1558 (items (plstore-find store search-spec))
1559 (item-names (mapcar #'car items))
1560 (items (butlast items (- (length items) max)))
1561 ;; convert the item to a full plist
1562 (items (mapcar (lambda (item)
1563 (let* ((plist (copy-tree (cdr item)))
1564 (secret (plist-member plist :secret)))
1568 (lexical-let ((v (car (cdr secret))))
1572 ;; ensure each item has each key in `returned-keys'
1573 (items (mapcar (lambda (plist)
1576 (mapcar (lambda (req)
1577 (if (plist-get plist req)
1584 ;; if we need to create an entry AND none were found to match
1588 ;; create based on the spec and record the value
1590 ;; if the user did not want to create the entry
1591 ;; in the file, it will be returned
1592 (apply (slot-value backend 'create-function) spec)
1593 ;; if not, we do the search again without :create
1594 ;; to get the updated data.
1596 ;; the result will be returned, even if the search fails
1597 (apply 'auth-source-plstore-search
1598 (plist-put spec :create nil)))))
1601 (dolist (item-name item-names)
1602 (plstore-delete store item-name))
1603 (plstore-save store)))
1606 (defun* auth-source-plstore-create (&rest spec
1608 secret host user port create
1610 (let* ((base-required '(host user port secret))
1611 (base-secret '(secret))
1612 ;; we know (because of an assertion in auth-source-search) that the
1613 ;; :create parameter is either t or a list (which includes nil)
1614 (create-extra (if (eq t create) nil create))
1615 (current-data (car (auth-source-search :max 1
1618 (required (append base-required create-extra))
1619 (file (oref backend source))
1621 ;; `valist' is an alist
1623 ;; `artificial' will be returned if no creation is needed
1627 ;; only for base required elements (defined as function parameters):
1628 ;; fill in the valist with whatever data we may have from the search
1629 ;; we complete the first value if it's a list and use the value otherwise
1630 (dolist (br base-required)
1631 (when (symbol-value br)
1632 (let ((br-choice (cond
1633 ;; all-accepting choice (predicate is t)
1634 ((eq t (symbol-value br)) nil)
1635 ;; just the value otherwise
1636 (t (symbol-value br)))))
1638 (auth-source--aput valist br br-choice)))))
1640 ;; for extra required elements, see if the spec includes a value for them
1641 (dolist (er create-extra)
1642 (let ((name (concat ":" (symbol-name er)))
1643 (keys (loop for i below (length spec) by 2
1644 collect (nth i spec))))
1646 (when (equal (symbol-name k) name)
1647 (auth-source--aput valist er (plist-get spec k))))))
1649 ;; for each required element
1650 (dolist (r required)
1651 (let* ((data (auth-source--aget valist r))
1652 ;; take the first element if the data is a list
1653 (data (or (auth-source-netrc-element-or-first data)
1654 (plist-get current-data
1655 (intern (format ":%s" r) obarray))))
1656 ;; this is the default to be offered
1657 (given-default (auth-source--aget
1658 auth-source-creation-defaults r))
1659 ;; the default supplementals are simple:
1660 ;; for the user, try `given-default' and then (user-login-name);
1661 ;; otherwise take `given-default'
1663 ((and (not given-default) (eq r 'user))
1666 (printable-defaults (list
1669 (auth-source-netrc-element-or-first
1670 (auth-source--aget valist 'user))
1671 (plist-get artificial :user)
1675 (auth-source-netrc-element-or-first
1676 (auth-source--aget valist 'host))
1677 (plist-get artificial :host)
1681 (auth-source-netrc-element-or-first
1682 (auth-source--aget valist 'port))
1683 (plist-get artificial :port)
1685 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1687 (secret "%p password for %u@%h: ")
1688 (user "%p user name for %h: ")
1689 (host "%p host name for user %u: ")
1690 (port "%p port for %u@%h: "))
1691 (format "Enter %s (%%u@%%h:%%p): " r)))
1692 (prompt (auth-source-format-prompt
1694 `((?u ,(auth-source--aget printable-defaults 'user))
1695 (?h ,(auth-source--aget printable-defaults 'host))
1696 (?p ,(auth-source--aget printable-defaults 'port))))))
1698 ;; Store the data, prompting for the password if needed.
1701 (or (eval default) (read-passwd prompt))
1702 (if (stringp default)
1704 (if (string-match ": *\\'" prompt)
1705 (concat (substring prompt 0 (match-beginning 0))
1706 " (default " default "): ")
1707 (concat prompt "(default " default ") "))
1712 (if (member r base-secret)
1713 (setq secret-artificial
1714 (plist-put secret-artificial
1715 (intern (concat ":" (symbol-name r)))
1717 (setq artificial (plist-put artificial
1718 (intern (concat ":" (symbol-name r)))
1720 (plstore-put (oref backend data)
1721 (sha1 (format "%s@%s:%s"
1722 (plist-get artificial :user)
1723 (plist-get artificial :host)
1724 (plist-get artificial :port)))
1725 artificial secret-artificial)
1726 (if (y-or-n-p (format "Save auth info to file %s? "
1727 (plstore-get-file (oref backend data))))
1728 (plstore-save (oref backend data)))))
1732 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1734 ;; deprecate the old interface
1735 (make-obsolete 'auth-source-user-or-password
1736 'auth-source-search "Emacs 24.1")
1737 (make-obsolete 'auth-source-forget-user-or-password
1738 'auth-source-forget "Emacs 24.1")
1740 (defun auth-source-user-or-password
1741 (mode host port &optional username create-missing delete-existing)
1742 "Find MODE (string or list of strings) matching HOST and PORT.
1744 DEPRECATED in favor of `auth-source-search'!
1746 USERNAME is optional and will be used as \"login\" in a search
1747 across the Secret Service API (see secrets.el) if the resulting
1748 items don't have a username. This means that if you search for
1749 username \"joe\" and it matches an item but the item doesn't have
1750 a :user attribute, the username \"joe\" will be returned.
1752 A non nil DELETE-EXISTING means deleting any matching password
1753 entry in the respective sources. This is useful only when
1754 CREATE-MISSING is non nil as well; the intended use case is to
1755 remove wrong password entries.
1757 If no matching entry is found, and CREATE-MISSING is non nil,
1758 the password will be retrieved interactively, and it will be
1759 stored in the password database which matches best (see
1762 MODE can be \"login\" or \"password\"."
1763 (auth-source-do-debug
1764 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1765 mode host port username)
1767 (let* ((listy (listp mode))
1768 (mode (if listy mode (list mode)))
1770 (format "%s %s:%s %s" mode host port username)
1771 (format "%s %s:%s" mode host port)))
1772 (search (list :host host :port port))
1773 (search (if username (append search (list :user username)) search))
1774 (search (if create-missing
1775 (append search (list :create t))
1777 (search (if delete-existing
1778 (append search (list :delete t))
1780 ;; (found (if (not delete-existing)
1781 ;; (gethash cname auth-source-cache)
1782 ;; (remhash cname auth-source-cache)
1787 (auth-source-do-debug
1788 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1790 ;; don't show the password
1791 (if (and (member "password" mode) t)
1795 found) ; return the found data
1796 ;; else, if not found, search with a max of 1
1797 (let ((choice (nth 0 (apply 'auth-source-search
1798 (append '(:max 1) search)))))
1802 ((equal "password" m)
1803 (push (if (plist-get choice :secret)
1804 (funcall (plist-get choice :secret))
1807 (push (plist-get choice :user) found)))))
1808 (setq found (nreverse found))
1809 (setq found (if listy found (car-safe found)))))
1813 (defun auth-source-user-and-password (host &optional user)
1814 (let* ((auth-info (car
1818 :user "yourusername"
1820 :require '(:user :secret)
1825 :require '(:user :secret)
1827 (user (plist-get auth-info :user))
1828 (password (plist-get auth-info :secret)))
1829 (when (functionp password)
1830 (setq password (funcall password)))
1831 (list user password auth-info)))
1833 (provide 'auth-source)
1835 ;;; auth-source.el ends here